i have some problems with collecting the data i fetch from database. Dont know how to continue.
What i did so far:
JQ:
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
data:{white:white}
});
});
});
PHP (requested page.php) so far:
$thing = mysql_real_escape_string($_POST["white"]);
..database connect stuff..
$query = "SELECT * FROM table1 WHERE parameter='$thing'";
if($row = mysql_query($query)) {
while (mysql_fetch_array($row)) {
$data[]=$row['data'];
}
}
What i dont know, is how to send out data and receive it with ajax.
What about errors when request is not succesful?
How secure is ajax call against database injection?
Thanks :)
You'll need a success parameter in $.ajax() to get a response once a call is made
$('#submit').click(function(){
var white = $('#white').val();
if(white == '')
{
// display validation message
}
else
{
$.ajax({
type:"POST",
url:"page.php",
data:{"white":white}
success:function(data){
$('#someID').html(data);
}
});
});
Whatever you echo (HTML tags or variables) in page.php will be shown in the element whose ID is someID, preferable to keep the element a <div>
In page.php, you can capture the value entered in the input element by using $_POST['white'] and use it to do whatever DB actions you want to
To send out data to you can write following line at the end :
echo json_encode($data);exit;
To receive response and errors when request is not successful in ajax :
jQuery.ajax({
type:"POST",
url:"page.php",
data:{white:white},
asyn: false,
success : function(msg){
var properties = eval('(' + msg + ')');
for (i=0; i < properties.length; i++) {
alert(properties[i]);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
For Feeling more safety do the following things:
1. Open a Session.
2. Detect Referrer.
3. Use PDO Object instead mysql_real_escape_string
4. Detect Ajax call :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !='xmlhttprequest') {
//Is Not Ajax Call!
}
Related
I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>
I am trying to send data to php file and I am using post and get to receive data base on if it is post or get.
The problem is that get is working and I click to receive data through post i do not receive anything.
php code process stops when it gets to GET then I send I POST and it does not respond to it. I can see ajax sends the data but php does not receive it when GET is working in php file.
php code:
if($_POST['id']){ show data}elseif{$_GET['id']{ get data}
jquery ajax:
// Youtube videos:
$(function() {
$('.image').click(function() {
var id = $(this).attr('id');
var msgbox = $("#video_status");
if(id.length > 5) {
$("#Video_status").html('<img src="assets/imgs/loading.gif" alt="loading ... " />');
$.ajax({
type: "POST",
url: "my_video.php",
data: 'id='+ id ,
cache: false,
success: function(msg){
$('#Video_status').html(msg);
if(msg ) {
msgbox.html(msg);
}else{
msgbox.html(msg);
}
}
});
}
return false;
});// End of youtube videos.
$(function() {
var loader = $("#Video_status").html('<img src="assets/imgs/loading.gif" alt=" loading ... " />');
var VideoWrap = $('#VideoWrap');
loader.fadeOut(1000);
$.get('my_video.php', '', function(data, status){
VideoWrap.fadeOut(1000);
VideoWrap.html(data);
VideoWrap.fadeIn();
});
return false;
});
});// get youtube video.
first check using isset
if(isset($_POST['id']))
{
//to show data echo/print something
echo $_POST['id'];
}
elseif(isset($_GET['id']))
{
//get data
}
try this
if($this->getRequest()->isPost()) {
}
if($this->getRequest()->isGet()) {
}
Why not something like this?
$postOrGetVar= $_GET['paramname'] ? $_GET['paramname'] : ($_POST['paramname'] ? $_POST['paramname'] : 'Param not sent via Post nor Get');
Simple, readable and easy.
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
Myproblem is when I click my first selectbox, after there is a value, it will trigger the second selectbox. I implement it in Ajax, but successfully render ,but my other textfield value is gone. How could I just render a specific part of the responde html(success ajax call)?
$(document).ready(function(){
if ($('#product_category').val() == 'Choose Category')
document.getElementById('product_subcategory').disabled = true;
$('#product_category').change(function () {
if ($('#product_category').val() == 'Choose Category')
document.getElementById('product_subcategory').disabled = true;
else
document.getElementById('product_subcategory').disabled = false;
data = $('#product_category').val();
//alert(data);
var param = 'category_name=' + data;
$.ajax({
url: MYURL,
data: param,
success: function(result) {
alert('Choose product subcategory');
alert(param);
$('body').html('');
$('body').html(result);
}
});
// window.location = MYURL?category_name="+data;
});
$('#product_subcategory').change(function () {
data = $('#product_subcategory').val();
// paramCategory = $(document).getUrlParam('category_name');
// alert(paramCategory);
$.get(MYURL, function(data){
alert("Data Loaded: " + data);
});
//window.location = MYURL?subcategory_name=" + data;
});
});
in my form, i use $_GET['category_name'] to get my value Ajax return value. I Debug in firebug, and it is successfully. I tried to render again the html, but my previous textarea's value and textfiel's value is gone since what i did is $('body').html(''); $('body').html(result);, So,how could I manage to get the success ajax return value, and use it in the PHP.
any confusion ,please tell me...
Thank you for spending ur time.
Hmm, I'm using a div and show the Div when it was return success ajax call.
the problem is here,
$('body').html('');
$('body').html(result);
you are blanking whole body and inserting new result. You have to change it to just
$('#second_select_box_id').html(result);
$('body').html('');
$('body').html(result);
This is emptying your page and inserting in it your result, I supose that what you really want to do is to load your second dropdown with the result, for that you'll need to do
$("#product_subcategory").html(result);
Of course, this will depend on what are your ajax function returning on result
You have two ways to do it.
Add the text from PhP while returning the data for Ajax call
Add the data back to the text box after loading the page..
data = $('#product_category').val();
//alert(data);
var param = 'category_name=' + data;
$.ajax({
url: MYURL,
data: param,
success: function(result) {
alert('Choose product subcategory');
alert(param);
$('body').html('');
$('body').html(result);
$('#product_category').val(data);
}
});
can you please try this
$(body).html('');
$(body).html(result);