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.
Related
I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard
I have a file called post-blog.php this is collecting the data and storing it in a variable called page.
var page = title + content+ image + datetime +categories;
I'm then sending this off to publish.php, if sent correctly send the user to that page.
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php";
}
});
return false;
This I my php script which is on the 2nd page (publish.php). How can I store the jquery data into php varible. So that I can display them on publish page.
<?php
if ( $_POST['page'] == true )
{
echo "Inserted";
}
?>
You can send this by setting data as follow:
data: {'page': page},
jQuery has some examples on the $.ajax and $.post page:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.post/
You can send data using query string variable in url like this
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php" + "?page=" + page ;
}
});
return false;
Then on publishing page you could get data using following code
if (isset($_POST['page']) && $_POST['page'] != '') {
var_dump($_POST['page']);
echo 'inserted';}
?>
you can pass your variable like this
var page = {
title : title,
content : content,
image : image ,
datetime : datetime ,
categories : categories
}
and then in php
<?php
if(isset($_POST["title"])){ // you can use content , image ,... same way
$title = $_POST["title"];
echo $title;
}
?>
and in ajax
success: function( response) { //response is the data which returned from php .. for sure (page) will work but just to be clear
alert(response);
//window.location.href = "publish.php";
}
if you want to use page as an array you can use
var page = [];
page.push(title);
page.push(content);
.......
then in php use
<?php
if (isset($_POST['page'])) {
print_r($_POST['page']);
}
?>
I have Jquery/Ajax Code which sends Text Fields Data to PHP Script. But i don't know how i can receive that data and process for Validation.
Here is the Ajax Code:
$("#button").click(function (e) {
var dataa = $("#survay").serialize();
var data = $("#yourName ,#emailAdress , #phoneNumber , #zipCode").serialize();
$.ajax({
type: "POST",
url: 'processRequest.php',
data: dataa,
beforeSend : function(){
$('.eDis').empty().append('<div class="loader"><img src="images/32.gif" /> Loading...</div>').show();
},
success: function (html) {
if(html !='1') {
$('.eDis').empty().append(html).addClass("actEr");
setTimeout(function(){
$('.eDis').removeClass("actEr")}, 5000);
}
if(html == '1') {
$('.eDis').empty().append('<div class="success">Your Message has been sent</div>').addClass("actEr");
window.location ='../thank-you.html';
}
if(html =='0') { $('.eDis').empty().append('Error..').addClass("actEr"); setTimeout(function(){
$('.eDis').removeClass("actEr")}, 3000);
}}
});
});
processRequest.php should be PHP script which will handle all the texts fields data.
If above Text fields data is valid then i want it to Proceed further and redirect the page to thank-you.html
.eDis is CSS class, which i want to use to display valid,Invalid fields information.
It is in HTML.
Based on your information, I can't give you exact code, but, this is what you can do:
<?php
if(isset($_POST['itemName']) && isset($_POST['anotherItemName']) /* ...and so on */){
if($_POST['itemName'] == $validSomething)
echo 'WOW!';
}
else
echo 'error';
?>
What you are "echoing" is what you get in "success" data in your javascript.
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
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!
}