Working with Ajax, PHP, and Javascript - javascript

I'm in no way, shape, or form anywhere near as close or experienced as most of you. However, my experience in PHP compared to Javascript is slightly better. So please excuse me, if my code seems mediocre or "newbie."
Anyways, I have a single page with a form with a simple input box and then two checkboxes. I'm working with ajax for the first time, and I was able to get my code to work, in a sense. In my PHP code, I have it run certain things depending on what checkbox is selected. However, with this ajax code (and/or PHP as well), when it executes my code it runs all of my code even if the checkbox is selected or not. I'm here asking if you see what I did wrong:
[index.php -> form code]
<form method="post" class="form-horizontal">
<fieldset>
<!-- Form Name -->
<legend>Enter the tweet URL below to begin using the service.</legend>
<div id="ajaxDiv" class="alert alert-success">We've successfully completed your request, check twitter now. Or, simply click here.</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="url">Tweet URL</label>
<div class="controls">
<input id="url" name="url" type="text" style="height:43px; width:100%; font-size:18px;" placeholder="" class="input-xlarge" required="">
<p class="help-block">The URL of the tweet we are favouriting or retweeting. <span style="font-size:15px;">Example: https://twitter.com/topIess/status/411632658683150336</span></p>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="control-group">
<label class="control-label" for="checkboxes">What would you like for that tweet?</label>
<div class="controls" required="required">
<label class="checkbox" for="checkboxes-0">
<input type="checkbox" style="margin-top:15px;" name="retweet" id="checkboxes-0" value="Retweet">
Retweets
</label>
<label class="checkbox" for="checkboxes-1">
<input type="checkbox" name="favorite" style="margin-top:15px;" id="checkboxes-1" value="Favourite">
Favourites
</label>
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="submit"></label>
<div class="controls">
<button type="submit" onclick="postStuff();" class="btn btn-inverse">Start Process... </button>
</div>
</div>
</fieldset>
</form>
<div id="status"></div>
[index.php -> javascript]
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var fn = document.getElementById("url").value;
var ln = document.getElementById("checkboxes-0").value;
var url = "handle1.php";
var ln1 = document.getElementById("checkboxes-1").value;
var vars = "url="+fn+"&retweet="+ln+"&favorite="+ln1;
hr.open("POST", url+"?x="+nn+"&y="+nn1, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "Processing...";
}
</script>
[handle1.php -> my PHP code]
<?php
/**
* #file
* User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/
require_once('twitteroauth/twitteroauth.php');
$con=mysqli_connect("host","user","","twtid");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM twitter");
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$connection[$row['id']] = new TwitterOAuth('ZG808c0pad0ar7wpgYPmA', 'BWHnOag1aWQtoYRBH5OtsI9m9Ghr3pTuMBo6z4ZNNP8', $row['key'], $row['secret']);
}
/* Create a TwitterOauth object with consumer/user tokens. */
/* $content = $access_token['oauth_token']. " " . $access_token['oauth_token_secret']; */
/* $content = $connection->get("account/verify_credentials"); */
$url1 = parse_url($_POST['url'], PHP_URL_PATH);
$url = explode("/", $url1);
/* If method is set change API call made. Test is called by default. */
$method = 'statuses/retweet/'.$url[3];
$amt = 18;
$sub = rand(1,2);
$amt1 = $amt-$sub-1;
for ($x=1; $x<=$amt; $x++)
{
if($_POST['retweet'] == "Retweet"){
$content = twitteroauth_row($method, $connection[$x]->post($method), $connection[$x]->http_code);
}
if($x == $amt) {
$done = "yes";
}
}
for ($x1=1; $x1<=$amt1; $x1++)
{
if($_POST['favorite'] == "Favourite"){
$content = $connection[$x1]->post('favorites/create', array('id' => $url[3]));
}
}

in your javascript you are posting the value property of your checkboxes, that is the wrong one to use in this situation (as the value of a checkbox is always the same). instead you should be checking if the checked property is true, as that defines if a checkbox is checked or not.

Related

Server Side Validation Show Success or Error message inline

I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.
html:
<?php
include('ajaxreturn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<body>
<form id="submit" onsubmit="submitForm(); return false;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="Name">Name</label>
<input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
<span class="text-danger"><?php echo $name_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="subject">Subject</label>
<input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
<span class="text-danger"><?php echo $subject_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control pt-0 pb-0" id="category">
<option>...</option>
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-1
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>
</div>
div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-2
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>
</div>
<div class="row">
<button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
</div>
</form>
<!-- Optional JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- <script src="main.js"></script> -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
php:
<?php
// Form Variables
$name = "";
$subject = "";
$category = "";
$classroom="";
//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Your Name";
} else {
$name = validation($_POST["name"]);
// Function calling and checking the letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Your name must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Your Subject";
} else {
$website = validation($_POST["subject"]);
// Function calling and checking the letters and whitespace
if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
$subject_error = "Subjets must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["category"])) {
$category_error = "Please select categoy";
} else {
$category = validation($_POST["category"]);
}
if (empty($_POST["classroom"])) {
$classroom_error = "Select the Class Room";
} else {
$classroom = validation($_POST["classroom"]);
}
}
function validation($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Ajax:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "name", _("name").value );
formdata.append( "subject", _("subject").value );
formdata.append( "category", _("category").value );
formdata.append( "classroom", _("classroom").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "ajaxreturn.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
Error:
ajaxform.php?name=&website=&submit=submit:78 Uncaught TypeError: Cannot read property 'value' of null
at submitForm (ajaxform.php?name=&website=&submit=submit:78)
at HTMLButtonElement.onclick (ajaxform.php?name=&website=&submit=submit:58)
submitForm # ajaxform.php?name=&website=&submit=submit:78
onclick # ajaxform.php?name=&website=&submit=submit:58
ajaxform.php?name=&website=&submit=submit:78
formdata.append( "category", _("category").value );
onclick # ajaxform.php?name=&website=&submit=submit:58
<button name="submit" id="submit" onclick="submitForm()" value="submit" type="submit" class="btn btn-success">submit</button>
Category with Select options Tag
<option value=1>1</option>
<option value=1>1</option>
<option value=1>1</option><option value=1>1</option>
Trying changing the ajax inside to this.
if (this.status == 200 && this.readyState == 4) {
this.responseText;
The rest of your code above looks right. I have never seen xmlhttprequest used having a variable name inside, Usually it looks like
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "ajaxreturn.php", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
I dont know enough php to take a look at your server side validation. I use NodeJs for all of that. Did you console log your this.responseText to see what variable your server is sending back. Also don't have your submit button submit, that is also your problem, have it run the onSubmit function. So...
<button id="submit" name="submit" onclick="submitForm()" class="btn btn-success">submit</button>
and take the onSubmit off of your form tag. I believe this will fix your issues.
When you submit the form, thats what opens a new page, when you just run the function with ajax, that won't make the browser open a new page. It just happens in the background.

Passing form element to javascript and then running jquery/ajax to pull from DB..phew

I am trying to take a zip code from my form and then submit it to javascript/jquery that will then pull data from the database with that zip code. I copy pasted code from w3schools and changed a few names, also referred to some SO code to take in the form element from a submit button click with an ID..
The issue is that the returned stuff from search.php page is not being displayed in the tag that has the eventsReturned ID. Also, I am not sure that the searchEvents() method is receiving the zip?
Here is what I have so far.. all help is appreciated as usual:
Javascript in index.php page --
<script>
$(document).ready(function() {
$('#searchEventsBtn').click(function() {
searchEvents($('#zip').val());
});
});
$(function searchEvents(zip) {
if (zip == null) {
document.getElementById("eventsReturned").innerHTML = "No events found in that zip code..";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("eventsReturned").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","search.php",true);
xmlhttp.send();
}
});
</script>
index.php page --
<form name="searchEvents" method="post">
<input type="text" class="form-control" placeholder="Enter a zipcode" name="zip" id='zip'>
<a class="btn btn-default" style='border:1px solid #EC811C;' role="button" data-toggle="collapse" href="#advancedSearch" aria-expanded="false" aria-controls="collapseExample">
Advanced Options
</a>
</div>
<div class="col-md-4"></div>
</div>
<div class="collapse" id="advancedSearch">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<select class="form-control" name="category">
<option>All Categories</option>
<option>Bar/Nightclub</option>
<option>Local Public Event</option>
<option>Private Event/Invite Only</option>
<option>Restaurant/Dining</option>
<option>Sporting/Outdoor Activity</option>
</select>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-2">
<div class="form-group">
<div class="input-group date" id="startDate">
<input type="text" class="form-control" name="startDate" placeholder="Start End"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="input-group date" id="endDate">
<input type="text" class="form-control" name="endDate" placeholder="End Date"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
<script>
$(function () {
$('#startDate').datetimepicker({
format: 'YYYY-MM-DD'
});
$('#endDate').datetimepicker({
format: 'YYYY-MM-DD'
});
});
</script>
<br>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="submit" id='searchEventsBtn' name="submit" class="btn btn-primary btn-lg btn-block">Search</button>
</div>
<div class="col-md-4"></div>
</div>
</form>
search.php page called by javascript/jquery --
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
if ($_POST["zip"] == ""){
echo "<script>
alert('Zip code must be entered.');
</script>";
}
else if ($_POST["zip"] < 10000 || $_POST["zip"] > 99999){
echo "<script>
alert('Zip code must be a valid number.');
</script>";
}
else {
$zip = $_POST["zip"]; //Outside for tab implementation later.
$category = $_POST["category"];
$startDate = $_POST["startDate"];
$endDate = $_POST["endDate"];
}
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
//EVENTS IN ZIP CODE #####
$sql = "SELECT id, name, DATE_FORMAT(date, '%W, %b %e %Y %l:%i %p') date, date orderByDate, shortDesc, summary, street, city, state, zip, private
FROM events
WHERE zip = ".$zip."
AND approved = 1
AND date > sysdate()
AND NOT EXISTS (SELECT 1 FROM signup WHERE signup.eid = events.id and signup.customer= ".$userId.")";
//Add in cateogry filtering to sql query
if ($category == "All Categories"){
//do nothing, show all categories
}
else if ($category == "Bar/Nightclub"){
$sql = $sql." AND category = 'Bar/Nightclub'";
}
else if ($category == "Local Public Event"){
$sql = $sql." AND category = 'Local Public Event'";
}
else if ($category == "Private Event/Invite Only"){
$sql = $sql." AND category = 'Private Event/Invite Only'";
}
else if ($category == "Restaurant/Dining"){
$sql = $sql." AND category = 'Restaurant/Dining'";
}
else if ($category == "Sporting/Outdoor Activity"){
$sql = $sql." AND category = 'Sporting/Outdoor Activity'";
}
//Add Date filtering
//If start and end dates are not null, then you have a date range to search for
if ((!$startDate == null) && (!$endDate == null)){
$sql = $sql." AND date BETWEEN '".$startDate." 00:00:00' AND '".$endDate." 23:59:59'";
}
//start date is set without an end date
else if ((!$startDate == null) && ($endDate == null)){
$sql = $sql." AND date > '".$startDate." 00:00:00'";
}
//start date is null but have and end date
else if (($startDate == null) && ($endDate != null)){
$sql = $sql." AND date < '".$endDate." 23:59:59'";
}
//start and end dates are null
else if (($startDate == null) && ($endDate == null)){
//dont add a date filter, do nothing
}
//Add the end part of the sql
$sql = $sql." ORDER BY orderByDate asc";
//Run the query
$result = mysqli_query($db,$sql);
//if there are records returned..
if ($result->num_rows > 0) {
echo "<h1 class='text-center'>Events in ".$zip."</h1><hr>";
//count the number of panels put into the results, this is based on col-md-4 for each panel (3 panels, 4 col width each)
$counter = 0;
while($row = $result->fetch_assoc()) {
if ($counter == 0){
echo "<div class='row'>";
}
echo "
<div class='col-md-4'>
<div class='panel panel-default'>
<div class='panel-body'>
<div class='media'>
<div class='media-left media-top'>
<a href='#'>
<img class='media-object' src='...' alt='...'>
</a>
</div>
<div class='media-body'>
<h4 class='media-heading'><b><a href='eventInfo.php?eventId=".$row["id"]."'>".$row["name"]."</a></b></h4>";
if ($row["private"] == 1){
echo "Private Address";
} else {
echo $row["street"].", ".$row["city"].", ".$row["state"]." ".$row["zip"];
}
echo "
</div>
</div>
<br>
<p class='text-left'><b>Date and Time: </b>".$row["date"]."</p>
<p class='text-left'><b>Description: </b>".$row["shortDesc"]."</p>
<form method='post' action='u_signup.php' name='signup'>
<div class='text-center'>
<button class='btn btn-primary' type='submit' name='submit' value='".$row["id"]."'>Signup For Event</button>
</div>
</form>
</div>
</div>
</div>
";
if ($counter == 2){
//reset row counter/setter
$counter = 0;
echo "</div>";
} else {
$counter++;
}
}
}
else {
if (isset($zip)){
echo "<h1 class='text-center'>Events in ".$zip."</h1><hr>";
echo "<p class='text-center'>No events for that search critera. Consider <a href='create.php'>creating an event</a> in your area!</p>";
}
}
?>
Ok it seems you are new to this kind of thing so I am going to try and explain a couple of things. First off, I see you have jquery but trying to do things with pure javascript because you probably copied it.
Jquery can make things a lot easier and cross browser friendly, that is why we use it. So if you want to send data to the server rather use Jquery, like this:
$.post('search.php', {'my_zip_code': zip}, function(data, result, xhr){
$("#eventsReturned").html(data); // notice how I use jquery instead of getElementById
});
Ok so now that we got that out of the way. It seems like the main problem is you not being able to debug code properly. It is really easy, so here is how you do it.
If you use Google Chrome to test with, you will notice in the developer tools (F12) there is a console tab. If you want to display something in there you can use:
console.log('anything');
So if you want to let say see what was returned from the server (search.php) you would just use this in the code I gave you above:
console.log(data); // data is what was returned from the jquery ajax post
That will display the variable in the console and you can check it out and see what was returned.
Now, if you want to see if your server received the data in the first place it is also pretty easy to do. Again in your Google Chrome developer tools look for the tab called network. Now in your network tab, if you sent the server an ajax request it will be listed there, normally with the name of the page you requested, like search.php.
When you click on this request it should show you what was sent in the first place, but also there should be a tab with responses... now if you see nothing in there, you can go to your php file and type in the following:
var_dump($_POST);
That will show you everything that was posted to the file, including the zip code (if it was ever sent). That output should be inside the response tab like I mentioned above.
Knowing how to debug code and find problems is the best way forward, not just some solution someone gives you here.
Goodluck

Passing variable back to page with ajax

I have a page (form.php) that uses ajax to post some form data to a page (insert.php) which is then inserted into a mysql database.
I now want to be able to do a simple equation on insert.php and return the result as a variable back to form.php. Can anyone tell me how I return $variable back to form.php as a variable that I can then use?
Form.php
//Stripped down for ease of reading
<script>
$(document).ready(function(){
$("#message").hide();
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('insert.php', formdata,
function(data){
$("#message").html(data);
$("#message").fadeIn(500);
return false;
});
});
</script>
//The Form
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="bill_cost"></label>
<div class="col-md-8">
<input id="bill_cost" name="bill_cost" type="text"
placeholder="Bill Cost" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1"
class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<div id="message">
insert.php
<?php
//Connection script would be here
$bill_cost=$_POST['bill_cost'];
//Insert into Database
$stmt = $db_conx->prepare('INSERT INTO mytable set bill_cost=?);
$stmt->bind_param('s',$bill_cost);
$stmt->execute();
if($stmt){
//Count Rows
$sql="SELECT bill_cost FROM mytable";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
//Do some maths (for example )
$variable=$rowcount/100
//echo message BUT how to send it as a variable?
echo "<h1>Answer is ".$variable."</h1>";
}
else{ echo "An error occurred!"; }
?>
If you want to send data which shall be parsed by your script, you should send your data as json. Sent every output as json, even the errors. For that you will have to send the content-type header. E.g:
// sending output
header('Content-Type: text/json');
echo json_encode(array("my_var" => "This is the content of the var"));
or sending an error:
// or sending error
header('Content-Type: text/json');
echo json_encode(array("error" => "This is my error"));
On the client side you can use $.getJSON (Documentation) to automatically parse the response as json:
// send request and get response
$.getJSON("insert.php", formdata, function(data) {
// check for errors
if (typeof data["error"] == "undefined") {
// check if my_var is set?
if (typeof data["my_var"] != "undefined") {
// use data["my_var"]
}
}
});

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

How to give user defined timeout message when max execution time over by handeling properly

I am designing custom query page where user can fire query and get the desired result.
In my database I have crores of records obviously it takes time around 10 to 15 minutes to execute .
After timeout page gets terminated and code below the php script is not executed so it is not showing below design and footer.
Please let me know how to handle timeout properly so that whole page executes and gives proper user defined timeout message and also below design and footer if execution time exceeds.
Here is what I am trying to do...
<form onsubmit="custom.php;" id="usrform" method="post">
<textarea id="tarea" placeholder=" Example: select malindex,malname,virustype,filetype,count from CT_DETECTIONS;" name="query" form="usrform" style="width:800px;height:100px;"></textarea>
<br>
<br><input type="submit" value="Submit Query" onclick="validate();">
</form>
<br>
<?php
//DB connection
if(isset($_POST['query'])&& $_POST['query']!='')
{
$x = $_POST['query'];
$result = mysqli_query($con,$x);
if(!$result)
{
$msg='<b>Error: </b>Invalid query. Enter a valid query. Please refer to Database Schema <b style="color:black;">here</b> ';
}
else
{
$x="<b>Query: </b>" .$_POST['query'];
//fetching rows and drawing google chart table
<?php echo $x;
}
}?>
<div id="valid" style="color:red;">
<?php echo $msg; ?>
</div>
<div style="color:red">
<lable id="myP"> </lable>
</div>
</div>
</div>
<div id="visualization" style="width:800px; height: 450px;color:black;margin-left:22px;"></div>
</div>
</div>
Please let me know how to handle page termination due to timeout
You could either change the time limit by using set_time_limit(60*60); www.php.net which will set it to 1h or take a look on this article on Stackoverflow.
You can check for the maximum execution time value from this script:
if(ini_get('max_execution_time')</*Set value do you want(integer)*/{
//Overlimit
}
else{
//Your script
}
Using AJAX :
<?php
//DB connection
if(isset($_POST['query']))
{
// MUST BE FIRST OUTPUT (nothing before)
header('Content-type: text;charset=UTF-8');
$x = $_POST['query'];
$result = mysqli_query($con,mysqli_real_escape_string($con, $x));
if (!$result)
{
echo '<b>Error: </b>Invalid query. Enter a valid query. Please refer to Database Schema <b style="color:black;">here</b> ';
exit();
}
//fetching rows and drawing google chart table
echo $x;
exit();
}
?>
<form onsubmit="return submitUsrForm();" id="usrform" method="post">
<textarea id="tarea" placeholder=" Example: select malindex,malname,virustype,filetype,count from CT_DETECTIONS;" name="query" form="usrform" style="width:800px;height:100px;"></textarea>
<br>
<br><input type="submit" value="Submit Query" onclick="validate();">
</form>
<br>
<b>Query: </b><span id="query"></span>
<div id="valid" style="color:red;">
</div>
<div style="color:red">
<lable id="myP"> </lable>
</div>
</div>
</div>
<div id="visualization" style="width:800px; height: 450px;color:black;margin-left:22px;"></div>
</div>
</div>
<script type="text/javascript">
function validate() { return true; }
function submitUsrForm() {
// clear content between each query
document.getElementById("valid").innerHTML = "";
document.getElementById("visualization").innerHTML = "";
// get textarea content
var query = document.getElementById("tarea").value;
// Create AJAX request
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "custom.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("query=" + encodeURI(query));
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// success
document.getElementById("visualization").innerHTML = xhr.responseText;
}
else {
// error
document.getElementById("valid").innerHTML = xhr.responseText;
}
}
}
return false;
}
</script>
To test execution timeout you can add after header :
ini_set('max_execution_time',1 );
sleep(3);

Categories

Resources