NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes
Related
Ok so, some context. My college started doing some "learning on the job" type classes, and it's becoming a pain because it's like an internship without any sort of capacitation. Just my luck I was assigned a project I'm barely prepared for.
Right now I've been asked to join together an old Jamit Job Board with the login system of the place. Basically verify first if the user exist in the test database, then check if they exist in the local jobboard database. The problem is I don't have any ajax experience since it's not a topic we have touched in my classes. Sad, I know.
I was trying using cURL but was told by the supervisor it wouldn't work.
public function validar_request($Username,$Password) {
$Username = ($_REQUEST['username']);
$Password = md5(stripslashes($_REQUEST['password']));
function httpGet($url,p){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$respuesta1 = httpGet("http://www01pruebasweb.fod.ac.cr/upe/templates/interfaces/ConexionFramework.php?procedimiento=nombreUsuarioExiste&username=".$Username);
The URL will return a 1 is the user exists in the testing database, 0 if not. I was thinking on doing a series of If else that if response = 1, then proceed to login, else donĀ“t since its like a 3 step verification process. First if the user exists, then if the password exists, and lastly if both tables in both databases match.
Response I get in the browser looks like this.
If the user usuario_01 exists then I should get a one. The idea me and a teammate had was to use curl to store the 1 into a variable in php and compare it but it's not working. Specially with the mess that is, for me, the other code for logging of Jamit. I mainly have experience with Java, not web development so as you can understand I'm very overwelmed.
I was trying to contact support from Jamit to see if they had any help, but they aren't active since 2013. Though not sure how much help they would be.
Not sure if necessary but part of the code for logging of Jamit is this
function validate_candidate_login($login_page='') {
global $login_output;
if ($login_output) { echo $login_output; return; } // this function was buffered
if ($login_page=='') {
$login_page = JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."index.php";
}
global $label;
$Username = ($_REQUEST['username']);
$Password = md5(stripslashes($_REQUEST['password']));
$sql = "Select * From users Where Username='".jb_escape_sql($Username)."'";
$result = JB_mysql_query($sql);
// init $row
if (mysql_num_rows($result)==0) {
$row = array();
} else {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
}
JBPLUG_do_callback('val_can_set_pass', $Password); // Note for Plugin authors: Password is passed by refrence. Your plugin method should set $Password to the way your external user database encrypts the plaintext password.. eg $Password = md5($_REQUEST['password']); for phpBB
JBPLUG_do_callback('val_can_login', $row); // Note for Plugin authors: $row argument is passed by reference, which is the row of your users table. The row is populated if username/pass are valid, $row['Username'] and $row['Password'] are set for the code below and should come from your external database. You may also set $row['Validated'] too
if ((!$row['Username']) && ($_REQUEST['silent']=='')) {
$label["c_login_invalid_msg"] = str_replace('%LOGIN_PAGE%', $login_page, $label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%FORGOT_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."forgot.php",$label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%SIGNUP_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."signup.php",$label["c_login_invalid_msg"]);
echo '<p style="text-align:center; ">'.$label["c_login_invalid_msg"]."</p>";
} else {
if ($row['Validated']=="0") {
$label["c_login_notvalidated"] = str_replace('%BASE_HTTP_PATH%', JB_BASE_HTTP_PATH, $label["c_login_notvalidated"]);
echo '<p style="text-align:center; ">'.$label["c_login_notvalidated"].'</p>';
} else {
if (($Password === $row['Password']) || ((JB_ALLOW_ADMIN_LOGIN=='YES')&&(JB_ADMIN_PASSWORD===$_REQUEST['password']))) {
JBPLUG_do_callback('val_can_login_sync', $row); // Note for Plugin authors: Initialize $row with a Jamit user row. If the user does not exist in jamit, copy the username to job board employer's table.
JBPLUG_do_callback('val_can_login_set_session', $row); // Note for Plugin authors: set session variables for your external database (successful login)
JB_set_candidate_session($row); // set session for the candidate
$label['c_login_welcome'] = str_replace ("%FNAME%", JB_escape_html($_SESSION['JB_FirstName']), ($label['c_login_welcome']));
$label['c_login_welcome'] = str_replace ("%LNAME%", JB_escape_html($_SESSION['JB_LastName']), ($label['c_login_welcome']));
$label['c_login_welcome'] = str_replace ("%USERNAME%", JB_escape_html($_SESSION['JB_Username']), ($label['c_login_welcome']));
if (isset($_REQUEST['page'])) {
$label['c_login_welcome'] = preg_replace('/index\.php/i', htmlentities($_REQUEST['page']), $label['c_login_welcome']);
}
if ($_REQUEST['silent']=='') {
echo '<p style="text-align:center; ">'.$label["c_login_welcome"].'</p>';
}
} else {
$label["c_login_invalid_msg"] = str_replace('%LOGIN_PAGE%', htmlentities($login_page), $label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%FORGOT_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."forgot.php",$label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%SIGNUP_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."signup.php",$label["c_login_invalid_msg"]);
if (strpos($login_page, 'apply_iframe.php')!==false) {
$label["c_login_invalid_msg"] = str_replace('_parent', '_self', $label["c_login_invalid_msg"]);
}
echo '<div style="text-align:center;">'.$label["c_login_invalid_msg"].'</div>';
}
}
}
}
Ok cool - per the comments you're looking to get started with AJAX (Asynchronous Javascript And XML). I would highly recommend linking jQuery to your html page to get started - it will make AJAX calls MUCH easier.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Awesome, now we have jQuery loaded, which allows you to make an ajax call with a simple function.
So now we need to get values from the browser to the server. How do we do that? There are 2 approaches I would recommend:
1 - Use JSON (Javascript Object Notation) to send data to the server with key/value pairs. PHP is great for working with JSON.
2 - Serialize a form using jQueries $(formElement).serialize() function. This turns forms into key/value pairs and you can then receive the data using PHPs $_POST['keyOfFormField']
So I'm going to assume you're going with the JSON approach, which is always preferable in my opinion.
If you're unfamiliar with javascript, JSON format looks like this:
var jsonExample = {'Im a key': 'and im its value'};
This is how you represent an object literal in javascript, and we can send these to the server and store them in an associative array in PHP.
So, on to the ajax call. I will leave it up to you to research ways of getting your data into JSON format. It should be really simple.
In jQuery, an AJAX call looks like this:
$.ajax({
url: 'urlOfServerFile.php',
async: true,
data: JSON.stringify({'Im a key': 'Im its value'}),
type: "POST",
datatype: 'json',
success: function (json) {
json = JSON.parse(json);
//The server sent you back some data, do something with it!
},
error: function () {
alert("Please check your internet connection and try again");
}
});
So what is this doing?
$.ajax() is a function. In jQuery, you basically get access to this really awesome object, which is the jQuery object (it's also represented by the $ sign). So, $.ajax() is the same thing as saying jQuery.ajax()
The $.ajax() function takes an object as an argument. Remember that the {} is how we encapsulate an object in javascript.
The documentation for this object can be found here: http://api.jquery.com/jquery.ajax/
Basically, we need to tell the $.ajax() function a few things:
url - where are we sending this request?
async - will this request be sent asynchronously?
data - what data are we sending to the server?
type - what type of HTTP request are we sending this data in (POST, PUT, GET, etc)
datatype - what type of data are we sending?
success - what do we do if the request is successful?
error - what do we do if the request fails?
Well, at this point we've successfully sent data from browser to server asynchronously. How do we handle this in PHP? Here's how:
$input = json_decode(file_get_contents('php://input'), true);
This variable, $input is now an associative array with all of the JSON key/value pairs that we sent over. So, now we can store some of those values in variables like this:
$randomVariable = $input['im a key'];
I hope this post will get you started with AJAX. Once you get the hang of it, it's a really intuitive technology that will make your applications WAY better.
What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.
EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..
Okey, this is what I've got.
<?php
$options[1] = 'jQuery';
$options[2] = 'Ext JS';
$options[3] = 'Dojo';
$options[4] = 'Prototype';
$options[5] = 'YUI';
$options[6] = 'mootools';
That is my array, but I'd like to make it a bit more dynamic so that the array is built according to input id, so he won't have to change the php-code whenever he want's another poll. How would I import those input id's and push them into an array?
To the extent I can understand your question, you could use JSON to pass the data from the client to the server like this:
JAVASCRIPT (using jQuery):
var arr = [];
arr.push("option1");
arr.push("option2"); // and so on..
//Use AJAX to send the data across ..
$.ajax({
url: 'poll.php?jsondata=' + encodeURIComponent(JSON.stringify(arr)),
success: function(data) {
// response..
}
});
});
I think that PHP script will put those options into a database or something for using it later on.
Now, in PHP(poll.php):
<?php
$options = json_decode($_GET['jsondata']);
//...
?>
I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}