POST Request PHP equivalent in AJAX / JQuery - javascript

I'm able to send some POST requests to a php file. On this php file, I use this to check if my POST request is what I want:
<?php
if(isset($_POST['message'])) {
// Some stuff here
}
?>
I would like to know if I can do the same thing in AJAX / JQuery ?
Not something like this:
<script>
$.post("page.php", $("form[name=addMessage]").serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
</script>
EDIT:
I don't want to send POST request in AJAX / JQuery. I just want to check if I receive a POST request, send from another page.
Indeed, I send a POST request with a field named "message". And I my question is: Is it possible to check if the field "message" is set, but not in PHP, in AJAX / JQquery.
Thank you so much for your help.
Regards,
Lapinou.

If I understand what you are trying to do: No.
Do you want to just listen for an incoming request in Javascript without calling any Ajax-methods? This is not possible. Javascript needs to be told that "I am sending a request now, and I want a response". It is not possible to say "If any request is sent, deal with it here".
Think about it. How would this work? If Javascript would listen to any request incoming, how would it know the difference between an user submitting a form and you sending a request using Postman?
Also, once you load the website in your browser, this is said to be clientside. Everything that happens after that is bound to your computer and your instance of the website. Any request sent to the site would be sent to the server, not your browser.

An other way of doing a post is this:
$.ajax({
type: "POST",
url: "page.php",
cache: false,
data: "message=" + $(".msgBox").val(), //Or Json format { "message" : $(".msgBox").val() },
success: function(html){
$(dashboard_id).html(html);
}
});

Try this:
$("form[name=addMessage]").submit(function(e) {
e.preventDefault();
$.post("page.php", $(this).serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
});
*Update
As per your comment you want to check POST value using JavaScript / jQuery, I don't think so you can access POST data using JavaScript / jQuery. But you want to mix php then you can do something like this
var post = '<?php json_encode($_POST); ?>';
if (post.message !== undefined) {
}
You have to put var post = '<?php json_encode($_POST); ?>'; in a php file

Related

I can't understand AJAX calls for the life of me [duplicate]

This question already has answers here:
What is AJAX, really?
(21 answers)
Closed 5 years ago.
Ok, pardon the dramatic title, but making AJAX calls has to be the most confusing thing to do for me in my coding journey so far.
I’m completing a project where a user enters a keyword into a search bar and results are returned using the Wikipedia API. I’ve watched several tutorials on making AJAX calls and gone over the documentation, but it’s just not clicking.
The main questions that go on in my head when trying to figure this out:
What the heck is supposed to go into an AJAX call and how do I find out? I've gone over the documentation and know that there are a number of settings that can be specified in an AJAX call, but how do I figure out what settings I need to use? What do these settings mean?!
I know this might be a stupid question to most, but I'm just starting out and want to learn!
This is honestly all I have and currently understand:
$(function() {
// make ajax request
$.ajax({
url: "https://en.wikipedia.org/w/api.php", // this is the API endpoint
dataType: json;
});
});
What is an AJAX request?
Ajax is a set of web development techniques using many web
technologies on the client side to create asynchronous web
applications.
With Ajax, web applications can send data to and retrieve from a
server asynchronously (in the background) without interfering with the
display and behavior of the existing page.
Think of an AJAX request the same way you would think about an HTTP request. You are simply requesting files, text, or any other resource that is located on a server.
Why should I use AJAX requests?
They provide benefits to user experience, functionality, and performance.
For example, let's say you are trying to build a text-messaging application. To build something like this, you will need to have the new text messages appear on the page without the user needing to do something. This is called: Dynamically loaded content.
This can be achieved with AJAX.
How can I make an AJAX request?
By using jQuery, a framework for Javascript, we can make the experience alot easier. Here's a basic AJAX request with jQuery AJAX.
$.ajax({ *properties* });
The AJAX method takes some properties:
URL: The source you want to pull information from.
Method: The request method you want to use. (POST, GET, PULL)
Data: The data you wish to send to the source.
There's a lot more, however for simplicity reasons I am only going to name those.
Let's say you want to create a login system without a page refresh. This is really simple!
First, we need to setup the backend.
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'USER' && $password == 'PASS') {
echo('success');
} else {
echo('failure');
}
}
Save this inside a file called login.php.
Second, let's setup the frontend.
<form method="POST" action="login.php">
<input name="username" type="text" placeholder="Username">
<input name="password" type="password" placeholder="Password">
</form>
We now have a foundation for an ÀJAX request. Before I implement it, let's talk about what the PHP and HTML are doing.
The HTML has a form, which has two inputs, username and password. As we can see from the attributes, the form will send the data to login.php using the POST method. The PHP will check if they're set, and if they're correct.
Unfortunately, this setup causes one of the most hated website features. THE REFRESH.
How can we solve this? AJAX Baby!
First, remove the attributes on the form.
<form>
<input name="username" type="text" placeholder="Username">
<input name="password" type="password" placeholder="Password">
</form>
Second, add a submit event listener.
$('form').submit(function(event) {
});
Third, add a preventDefault() on the event to stop the page refresh.
$('form').submit(function(event) {
event.preventDefault();
});
Fourth, get the form values.
$('form').submit(function(event) {
event.preventDefault();
var $form = $(this);
var username = $form.find('input[name="username"]').val();
var password = $form.find('input[name="password"]').val();
});
Fifth, add the AJAX.
$('form').submit(function(event) {
event.preventDefault();
var $form = $(this);
var username = $form.find('input[name="username"]').val();
var password = $form.find('input[name="password"]').val();
$.ajax({
url: 'login.php',
method: 'post',
data: { username: username, password: password },
success: function(response) {
alert(response);
}
});
});
This will send the data to the login.php file on form submission. If the values are set, the PHP will echo (or give the data to AJAX) the status. It will return success or failure depending on the username and password accuracy.
Hope this helped! It took forever.
Ok, I'm not an "Ajax master" but here is an example of how you can use it, I hope it will help you.
Imagine you have a simple log in form in HTML :
<form method="POST" name="connexion" id="connexion">
<input type='text' id='add_url' name="add_url" required/>
<label for="add_url">Add URL</label>
<input type="submit" name="sub_add" value="Add">
</form>
Now I have a.js file where I want to check if the value added is good and I want to show a result if it's okay, but I don't want to reload my page. So I will make an Ajax call :
function add_url () {
var data = $('input[name = "add_url"]').val(); // Here I select my input "add_url" and put the value on my var "data"
$.ajax({
type: "POST", // How I want to send my data on my php page
url: "mypage.php" // the name of the file where I will use this data
data: {"add" : data}, // The data I will use in my php, with the name "add"
dataType: "json", // The type of data I want to receive
success: function(response) {
// If my ajax call worked, I will do some code here
},
error: function (xhr, status, msg) {
// If my ajax call failed, I want to know why so I will use "xhr, status and msg" to have some information about why it failed
}
});
}
Now in my php, I will use the data send with ajax and build a JSON response :
// mypage.php
<?php
$url = $_POST['add']; // I put the data send in my var $url
// you do some code here with your data, for example I add the new URL in some array and the new array is $data
$result['status'] = "success"; // All is ok so I say it
$result['message'] = "All is ok !" // I add some message
$result['data'] = $data; // The data I will use in my JS
$result = json_encode($result); // I need a JSON as response, remember?
echo $result; // My response
?>
Now in my ajax function, if all is ok I can use what I send in the success part:
success: function(response) {
if (response.status === "success") { // I test if the status I send is "success"
alert(response.message); // The message I send
console.log(response.data); // I want to see in my console the data I receive
}
}
This is just an example, but I hope you have a better idea of how to use it :)
It is hard to answer this question here and write about the use of all configuration of AJAX. I would suggest you to learn about HTTP Request in general. How it works and what all headers are there and their use. There is this nice tutorial on HTTP requests and AJAX . Please look into https://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest--net-1634 . Keep on using and exploring the AJAX calls. You will learn it with the time.
This question is closed so I hope other newbies who are learning about ajax
and are not looking for jQuery solution will get some idea from this page.
Asynchronous Javascript And XML (AJAX) is something that runs without stopping your entire code execution (in short, AJAX is asynchronous).
In normal JavaScript, codes are executed synchronously. This means that one code cannot be executed before the codes before it have been executed.
However, in AJAX, the codes after ajax code are still executed, even though the ajax code has not finished executing.
jQuery's $.ajax method is basically the over-simplified JavaScript below:
function ajax(settings){
var ajax = new XMLHttpRequest(), // initializing AJAX constructor
header = 'application/x-www-form-urlencoded';
ajax.addEventListener('readystatechange', function(e){
if (this.readyState == 4){ // if request is ready
if (this.status == 200) // if request is successful
settings.success(this); // run `success` function
else // if request is unsuccessful
settings.fail(this); // run `fail` function
}
});
if (settings.dataType === 'json') header = 'application/json';
ajax.open(settings.type, settings.url, settings.async); // opens connection with the server
ajax.setRequestHeader('Content-Type', header); // sets ajax request header
ajax.send(settings.data); // sends data to server
}
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: true,
success: function(e){
alert('Ajax successful');
},
fail: function(e){
alert('Ajax failed');
}
});
The code above explains what AJAX is. The code below explains what asynchronous mean.
If ajax is set to be synchronous:
var a = 0;
a += 1;
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: false, // async is set to false
success: function(e){
a += 10;
console.log(a);
},
fail: function(e){
alert('Ajax failed');
}
});
a += 2;
console.log(a);
After a few seconds (because of awaiting server's response), the console will log two 13 in the console. This is because the a += 2 will only be executed after the ajax()'s execution has ended.
However, if ajax is set to be asynchronous:
var a = 0;
a += 1;
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: true, // async is set to true
success: function(e){
a += 10;
console.log(a);
},
fail: function(e){
alert('Ajax failed');
}
});
a += 2;
console.log(a);
The console will immediately first log 3, then after a few seconds, logs 13. This is because while the ajax() is waiting for the server's response, the a += 2 and the codes behind are still being executed, even though the ajax() is still executing (waiting for server's response). Once the server responds, it will then only execute the a += 10 and the other console.log(a).
Of course, to make meaningful ajax request, you will need some code at the server side.
Assuming we have a fake api from api.php:
if (isset($_POST['hello']) && isset($_POST['foo'])){
$array = [
'one' => $_POST['hello'],
'two' => $_POST['foo'];
];
}
echo json_encode($array);
Then in JavaScript:
ajax({
type: 'POST',
data: {
hello: 'world',
foo: 'bar',
},
success: function(response){
console.log(response);
},
});
The console will then log something similar to the following:
{
'one': 'world',
'two': 'bar',
}

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

jQuery/Ajax: How to send data to an url without showing data in web-developers

I have a litle shop basket where I can add products.
Here is my index.php
...<script type="text/javascript" src="function.js"></script>
<a title="Add to basket" onclick="add_product_to_cart('apple','1');" href="#">Apple</a><br>...
Here is the functions.js
function add_product_to_cart(item, id) {
var item = item;
var id = id;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
action: "add",
name: item,
id: id
},
success: function(data) {
//do something
}
});
};
When I click on "Apple", the parameters are send to the ajax, and they are visible for example in the Firefox-Web-Developer.
Is there a chance to hide these POST-parameters? Maybe to protect it from attacs from outside? Is my thinking maybe totally wrong how to add it to the basket? Thanks for any help!!
Here is a screenhot from my web-developer.
Web-Developer Firefox
You can't hide what is being logged in the Network tab of Chrome Developer Tools. Even if you could, a hacker could sniff the requests using Fiddler or other web proxy. Client side validation is nice, but not the end all. Most people wouldn't be trying to send requests to your server illegitimately but some will I suppose.
You really should be doing server side validation that data sent to the server is indeed valid. Don't rely on the client to do this as anyone can modify what is sent directly to the server. In your PHP code, you would do something like this:
function validate_data($data)
{
// other code here
if(!is_discontinued($data['product_id']))
add_to_cart($data['product_id']);
// other code after
}
function is_discontinued($product_id)
{
// do database query
$is_discontinued = lookup_product($product_id);
return $is_discontinued;
}
This is very barebones, but it should give you the idea of what needs to be done.
EDIT:
After looking at some of your recent comments, you may also like to include CSRF tokens to make sure that requests originate from your domain. These tokens are generated on the server and often stored in hidden fields in the form to be sent back to the server with each request. Then you validate the token on the server and after it passes validation, you perform your action.
Note, this will only slow down most hackers, but it can deter some who aren't dead set on performing illegitimate requests.
In terms of sending the value with AJAX requests, you would need to select your hidden field and add its value to the POST data. Your AJAX request would then look something like this:
function add_product_to_cart(item, id) {
var item = item;
var id = id;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
action: "add",
name: item,
id: id,
token: $('#csrf_token').val()
},
success: function(data) {
//do something
}
});
};
On the server (PHP), you would have something like this:
function get_csrf_token()
{
$token = md5(uniqid(rand(), TRUE));
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = $token;
}
else
{
$token = $_SESSION['token'];
}
return $token;
}
function valid_csrf_token()
{
if(isset($_POST['token'])){
if($_POST['token'] == $_SESSION['token'])
return true;
else
return false;
}
else {
return false; // no token was sent with the request
}
}
Then in your form, you would have your hidden field like this:
<input id="csrf_token" type="hidden" value="<?php get_csrf_token(); ?>" />
Finally, your original PHP validation function would include the CSRF token validation:
function validate_data($data)
{
// other code here
if(!is_discontinued($data['product_id']) && valid_csrf_token())
add_to_cart($data['product_id']);
else
header('HTTP/1.1 400 Bad Request', true, 400); // set status to bad request
// other code after
}
Note, setting the status to bad request is optional, but it will show the request was not as expected.
The answer is: No, there is no way you can hide the data you're sending to server using AJAX.
But this shouldn't be a problem, since you MUST validate everything on server.
You can validate things on client-side (for normal users) to have a easier/faster response on client, and to get less traffic on your server. But, as said above, you must revalidate everything on server, cause this is the only way you can ensure that, even if malicious data is sent to your server, your website will still work as expected.
Btw, you can even block/ban the users that are trying to make something different from what your not-modified client code usually does.

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

javascript json request with some parameters

So a simple question:
JavaScript needs to send to server that request:
myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}}
How I need to form url and data in Ajax?
Is this right?
var formData = {
"login":$("#field1").val(),
"pass":$("#field2").val()
};
$.ajax({
url:'http://myserver/scipt.php?LANG=EN&',
type:'GET',
data:'AGENT=' + $.toJSON(formData),
success: function(res) {
alert(res);
}
});
Thank you!
I'd recommend sending JSON via POST instead of GET. GET has some limitations that you want to avoid.
A part from that, yes, your code seems ok.
EDIT:
Sorry, your code is not ok.
Change the data line to:
data: $.toJSON(formData),
You need to send the data to the server in the form of a map ..
Your data is already in json format.. You need not do $.toJSON again
Instead of
data:'AGENT=' + $.toJSON(formData),
send it this way
data:{ 'AGENT' : {'Login' : formData } },
You need to URL encode any strings you want to pass through Ajax.
If jQuery works anything like a normal form, you also need to put all your query string data into data to avoid the existing query string being destroyed.
url:'http://myserver/scipt.php',
type:'GET',
data: {
"AGENT": $.toJSON(formData),
"LANG": "EN"
},
Note, you should use POST requests if you are transmitting user credentials. You don't want them cached or stored in server access.log files.

Categories

Resources