So, here is ajax setup that I have for my wordpress site.
Page_1.php:
<?php echo '<div class="button" data-post_date="'.$rh_post_date.'" data-post_author_id="' .$rh_author_id. '" data-post_id="' .$id. '">' ;?>
custom_js.js:
jQuery('.button').click(function(e) {
e.preventDefault();
var indiv_id = jQuery(this).data("post_id");
var indiv_post_author = jQuery(this).data("post_author_id");
var indiv_date = jQuery(this).data("post_date");
jQuery.ajax({
type: "GET",
url: upload_image.ajax_url,
dataType: 'html',
data: ({ action: 'rhmp_indi_form', post_id: indiv_id , post_author_id: post_author, post_date_id: indiv_date}),
success: function(data){
jQuery('#rh_pop').html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
Page_2.php:
<div id="rh_pop">
<?php
$page_2_post_id = $_REQUEST['post_id'];
$page_2_post_author_id = $_REQUEST['post_author_id'];
$page_2_post_date_id = $_REQUEST['post_date_id'];
?>
</div>
As you can see, when the button in the page_1.php is clicked, the data become variables in custom_js.js. These variables are then sent to the page_2.
Now, I know that this is not secure at all and can be hacked easily.
So, how do I send data such as data-post_date or post_author_id to another page via ajax using php?
First of Ajax is a technique that is used in javascript to send a httprequest to the php server. The server handles that request and sends back its result. Its the same as requesting a page normally but then its without reloading the page.
Creating variables in javascript with php for use with ajax doesn't mean that php is the one doing anything ajax related. Hope this clears up a missunderstand.
More info on this: https://en.wikipedia.org/wiki/Ajax_%28programming%29
Sending data to the server is never safe. You can make help features like you need to fill in this field with a name and go on. Or maybe even use a disable the submit button if there aren't 3 or more numbers in a field but this is all to help the user and to make it unlikely that the server will get requests that will never be valid anyway.
This is the reason why server side validation is always needed and client side validation is more of a user friendly thing and making sure the server doesn't get requests that can be detected from the client side already.
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.
I want to pass the ID to the urlstring via jQuery without refreshing jQuery and # tag so that I could get the ID via php $_get['ID'] function.
But the problem is that
If I use #, page did not get refreshed, however PHP did pick the ID from url.
If I don't use #, then php do picks the ID but Page get refreshed.
I want to pass an id to php without refreshing the page.
//javascript
function com(id) {
location.href = '#?ID=id'; //by this way way,page doesn't refresh, ID appears in the url string but ID is not picked by PHP as # is there
// location.href = '?ID=id'; this way way, ID appears in the url string , ID is also picked by PHP as # is there.But page get refreshed.
$.ajax({
type: "Post",
url: "getdata.php",
async: true,
cache: false,
success: function(data) {},
});
}
//php for getdata.php
<?php echo $_GET['ID']; ?>
You need to educate yourself about server-side vs. client-side operations. Javascript is client side. The server (running PHP in your case) knows nothing about what javascript is doing unless you send some information back. This can be accomplished via a page refresh or via ajax (put simplistically).
What you want is ajax which is an asynchronous request that goes back to the server. The server can then handle it and choose to pass information back to the page. Look into jQuery's ajax.
Update based on your updated comment:
function com(id) {
//forget about appending the id. This isn't doing anything.
//You can use it for informational purposes or so that if someone cuts and pastes
//the link you can handle it server side appropriately.
location.href = '#?ID=id';
//instead focus on this call. append your query string to the url
$.ajax({
type: "POST",
url: "getdata.php?ID=12345",
async: true,
cache: false,
success: function(data) {
alert(data); //should alert the id processed by php
},
});
}
I’ve a javascript file I’ve been using as an template for a site I’m working on and in that script there is a simple form validation where it – if no error occur – sends data to an PHP page called contact.php.
But I’m unsure on how I “grab” the data send from the JavaScript in my PHP site? The contact.php works – that is, if I, in my form, direct it directly to contact.php it sends the mail without problem. In that file I send the variables like this: $name = $_POST['formName']; and so on and in the end send it to the mail function.
The code in my JavaScript file where it sends the data and display a “successful” message on the same page is:
$.post("contact.php",
{ formFrom: FromValue, formName: NameValue, formMessage: messageValue },
function(data){
$("#loadingImage").fadeOut("fast", function() {
$("#loadingImage").before('<p>The message has been sucessfully send. Thank you!</p>');
});
}
);
The NameValue, messageValue, FromValue is set in the form validation like this var messageValue = $("#formMessage").val();.
Any help would be very much appreciated.
Sincere
- Mestika
Just use the jQuery AJAX call (this syntax is from jQuery 1.5.X):
$.ajax({
type: 'POST'
url: urlString,
data: {formFrom: FromValue, formName: NameValue, formMessage: messageValue}
}).success(function(data, status, xhr) {
var obj = eval('(' + data + ')');
//response as object
});
To send JSON back to the JavaScript, use this function in your PHP:
http://php.net/manual/en/function.json-encode.php
One other thing: as a rule of thumb, it's poor practice to use variable names like "FromValue." Initial capitalization is supposed to be used for class names, not variables (JavaScript developers borrowed this practice from Java).
I'm having a really difficult time understanding how this all works together. I've fiddled for a few days with this and have been unable to come up with any results. I'm trying to fill in a text field in a form, and when the form is submitted, I want to add the text to my sqlite db using ajax.
I understand that you need a $.get call in jquery which is triggered on the form's submit. That seems to work fine as I can trigger js alert boxes from there. However, when I pass the address of the php script which has lines to add to the sqlite db using PDO, nothing is added to the db. However, when I run this php script from using php cli, something will get added to the db.
I seem to be missing an essential step here. I would really appreciate it if someone could bridge this gap for me!
Edit:
As requested by Martin here's some code:
My php generates some list like this with a form in the middle:
<ul>
<li>hello</li>
<li id="formItem">
<form action="" method="post">
<input type=text name="content"/>
</form>
</li>
<li>world</li>
</ul>
Then my jquery code looks to add whatever is in the textbox right above it on the list does an ajax call. This is inside a $(document).ready(function(){.
$("form").submit(function() {
var inputText = $("input").val();
$.ajax({
type: "POST",
url: "add.php",
data: inputText,
success: function() {
$('#formItem').prev().after(
"<li>" + inputText + "</li>"
)}
});
});
My add.php file looks like this and it will insert something into my db if I execute the php script on the cli:
<?php
$base = new PDO('sqlite:todo.db');
$sql = $base->prepare("INSERT INTO ThisTable (content, priority) VALUES ('lolololol', 1);");
$sql->execute();
$base = null;
?>
Do not forget that HTTP is a stateless protocol. Each HTTP request you make to your webserver is treated the same. This stands for whether the HTTP request was made using AJAX or not.
What I'm trying to say is that AJAX is a client side implementation. All AJAX means is that you can interact with your webserver without having to reload your page. Implementing an AJAX request for the first time in JavaScript is often a brain bender, because the requirement of callbacks and the general asynchronous nature of the interaction makes it difficult to grasp.
On the server however, there should be nothing to worry about. An AJAX request is still an HTTP request, so whether you navigate to http://www.yourwebsite.com/ajax/interact.php?a=1&b=2 in your browser, or make a HTTP GET request using AJAX, your PHP script will still behave exactly the same. If you var_dump($_GET); in either situation, you will get an array whose a and b members equal 1 and 2 respectively.
If you can emulate the AJAX request in your browser successfully by navigating to the URL manually, that's the server work done.
Having established that, your JavaScript should look something like this:
$('#yourForm').bind('submit', function (event) {
jQuery.get('/ajax/interact.php', 'a=1&b=2', function (response) {
alert("AJAX request succeeded, response from the server was: " + response);
});
event.preventDefault();
});
Once you're confident using jQuery's AJAX methods, you might want to look at methods such as serialize() to help you out, and you can develop your jQuery code to something as follows:
$('form.ajax').live('submit', function (event) {
var self = $(this);
jQuery[(self.attr('method') || 'get').toLowerCase()](self.attr('action'), self.serialize(), function (response) {
alert("AJAX request succeeded, response from the server was: " + response);
});
event.preventDefault();
});
Hope this helps :)
Your submit function should return false;