Converting PHP/MySQL Request into jQuery AJAX Request - php

I am kicking myself in the arse here because i can't for the life of me figure it out...this is supposed to be a quick and dirty project, but, I decided i want to try something new, and I have little to no experience with the AJAX methods in jQuery...I spent quite literally 5 days trying to learn and understand how to appropriately implement the AJAX calls, but to know avail...I learned some basic stuff, but not what i need to execute the code below.
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
here is my form & php
HTML:
<form action="categories.php?action=newCategory" method="post">
<input name="category" type="text" />
<input name="submit" type="submit" value="Add Categories"/>
</form>
PHP:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
if ($_GET['action'] == 'newCategory') {
$categories = $_POST['category'];
$query = "SELECT * FROM categories WHERE category ='$categories' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
} else {
// Simply cleans any spaces
$clean = str_replace(' ', '', $categories);
// Makes it possible to add multiple categories delimited by a comma
$array = explode(",", $clean);
foreach ($array as &$newCategory) {
mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
}
echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
}
}
} else {
echo "<script>alert('Please Enter at Least One Category.')</script>";
}
}
?>

here's the proper syntax for making the call in the background and not submitting the form, but still sending/retrieving results.
$(function(){
$('form').submit(function(e){
e.preventDefault(); // stop default form submission
$.ajax({
url: 'categories.php',
data: 'action=newCategory',
success: function(data){
//here we have the results returned from the PHP file as 'data'
//you can update your form, append the object, do whatever you want with it
//example:
alert(data);
}
});
});
});
Also:
I would not do this ->
echo "<script>alert('Please Enter at Least One Category.')</script>";
Just do echo 'Please Enter at Least One Category.';
If you need to create an error system, you can do things like,
echo "Error 1001: <!> Please enter at least One Category!';
Then in your Ajax callback for 'success', we can split the returned object in <!>. Example to follow:
success: function(data){
if($(data+':contains("<!>")'){
var errMsg = $(data).split('<!>');
alert(errMsg[0]+' : '+errMsg[1]);
//above would output - Error 1001 : Please enter at least One Category!;
}
}

Related

AJAX Post To PHP File Not Returning Data On Success

this is the flow I am trying to accomplish:
Form completed -> Data Sent to PHP File With Data -> PHP File Takes Data, Queries API -> PHP File Then Returns Query Results back to Original Page as an echo.
The round trip time for this should be around 10 seconds. Here is my form, AJAX, and PHP file.
Form
<form id="query_form">
<input type="text" id="query_input" name="query_input" required>
<button id="send_btn" type="submit" name="send_query" value="Submit Request">
</form>
AJAX
<script type="text/javascript">
$(document).on("click", "button[id='send_btn']", function(e){
e.preventDefault(); // Prevents any default actions by clicking submit in a form.
var query = $("#query_input").val(); // Gets the value of an input
$.ajax({
type: "POST",
url: "run.php",
data: {query:query},
success: function(r){ alert(r); }
});
});
</script>
PHP
<?php
require('RestClient.php');
$term = "";
if(isset($_POST['query'])){
$term = $_POST['query']
try {
$client = new RestClient('https://api.dataforseo.com/', null, '#########', '###########');
$post_array = array("language" => "en","key" => $term); // This is the term to search, correct?
$sv_post_result = $client->post('v2/kwrd_sv', array('data' => $post_array));
$search_volume = $sv_post_result["results"][0]['sv'];
echo "<div id='results_div'>
<table id='results_table'>
<tr class='results_table_row'>
<td id='SEO_Search_Volume_Cell'>
$search_volume <span>Approximate Number Of Searches Per Month</span>
</td>
</tr>
</table>
</div>";
} catch (RestClientException $e) {
echo "\n";
print "HTTP code: {$e->getHttpCode()}\n";
print "Error code: {$e->getCode()}\n";
print "Message: {$e->getMessage()}\n";
print $e->getTraceAsString();
echo "\n";
echo "An Error Has Occured, Please Try Again Later";
exit();
}
}
?>
Obviously the data echo'd back needs to appear on the same page as the form, yet nothing comes back. Why would this be?
try posting the data in a 'string' format, e.g.
var query = $("#query_input").val(); // Gets the value of an input
var queryString = 'query='+ query; and then use it in your $.ajax call with: data: queryString,
pick-up the value with $_POST['query']

PHP AJAX Notifications if MySQL query returns no rows

Situation
I've got a working script that sends an ajax request to get_code.php. This script is run from the main page - index.php. The get_code.php script queries my MySQL DB for a row and then sends back the data to index.php.
Current code
jQuery in index.php
<script type="text/javascript">
$("#Code").click(function(){
var cde = $("#codeinput").val();
$.ajax({
method:'POST',
url:'get_code.php',
data: {va_code:cde},
dataType: 'json',
success: function(output_string){
$('#rtable').append(output_string);
$("#codeinput").val('');
var prc = $(".price:last");
prc.focus();
}
});
});
</script>
PHP script get_code.php
<?php
include('dbc.php');
$code = $_POST['va_code'];
$cq = mysql_query("SELECT * FROM variants where va_code='$code'")or die(mysql_error());
if(!$cq){
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
}elseif(!mysql_num_rows($cq)){
mysql_close();
echo json_encode('No results returned');
}else{
$output_string = '';
$output_string .= '<tr>';
while($row = mysql_fetch_assoc($cq))
{
$output_string .= '<td>'.$row['cost'].'</td>';
//etc. etc. lots more output here
}
$output_string .= '</tr>';
}
mysql_close();
echo json_encode($output_string);
?>
Problem
However, if no results are found for the query, nothing is returned on the page to notify the user. Ideally I'd like to open a modal, or display a div in which I can use the data the user input. I just can't work out for the life of me how to check if $cq returns no results, and if so then to display something on index.php like a notification saying 'Your code was not found'.
Appreciative of any help
You could return a result flag. This is a good logic and easy to understand.
If no row was found :
die(json_encode(['result' => false, 'error' => 'No code was found']));
If some code found :
die(json_encode(['result' => true, 'output' => $output_string]));
And in js :
...
success: function(data){
if (!data.result) {
alert(data.error);
} else {
$('#rtable').append(data.output);
$("#cmtcodeinput").val('');
var prc = $(".price:last");
prc.focus();
}
}
...
Hope it helps.

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

displaying records from a php file via jquery;

Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()

Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.

Categories