Using Ajax to run php function - javascript

Hi I am trying to create a button that will call a php function to add products to Shopify from web application
First this is my result.php file which is showing amazon products successfully
http://codepad.org/MPs4y1Qu
There you will find two important things
first <button type="button">add</button>and
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'create_product.php',
success: function(data) {
prompt(data);
}
});
});
});
</script>
The problem is when I click on Add Button it shows the HTML of the page but nothing happens on the create_product.php file. I want it to call that function. On the other hand my code on create_product is fine and working 100% separately but not with my web app.
here is my create_product.php code:
http://codepad.org/at7LtcMK

Your AJAX call will send data by POST or GET, then you can do anything with that and also return something to your script. It's simple like that.
http://api.jquery.com/jquery.ajax/
Let's work with examples. If you want to make A+B on your server you will need to have a form with inputs like this:
<form id="yourform">
<div><input name="A" type="text" /></div>
<div><input name="B" type="text" /></div>
</form>
Then you will program some script to say what your form will do on submit. As you're using jQuery, let's work with jQuery:
$("#yourform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST", //or "GET", if you want that
url: "yourfile.php",
data: $(this).serializeArray(), //here goes the data you want to send to your server. In this case, you're sending your A and B inputs.
dataType: "json", //here goes the return's expected format. You should read more about that on the jQuery documentation
success: function(response) { //function called if your request succeeds
//do whatever you want with your response json;
//as you're learning, try that to see on console:
console.log(response);
},
error: function(response) { //function called if your request failed
//do whatever you want with your error :/
}
});
});
But what're you doing on the server?
Well, I just want to return my input's, just to check. Here goes my PHP:
<?php
header("Content-type: application/json; charset=utf-8"); //that's required to return any JSON data
if(isset($_POST, $_POST['A'], $_POST['B']))
exit(json_encode($_POST));
else
exit("INVALID REQUEST.");
?>
That's the way you can send information with AJAX to execute something on PHP.

You can add the following ajax function into your script.Note that the ajax function sends a data with value triggerPHP to the page that you have the PHP code. So at the .php page that you run the php code you must set a code to "catch" in someway the triggerPHP data via $_POST[] superglobal and the execute whatever you want.
EG
if(isset($_POST['triggerPHP'])){
//execute the code here remember to echo json_encode(data)
}
JQuery ajax :
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
data:'triggerPHP',
dataType: "json",
url: 'create_product.php',
success: function(data) {
prompt(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});

Related

How to post to php with ajax, I consistently get error 400 bad request?

I am trying to send a "POST" request to my backend PHP code, which resides in functions.php in Wordpress. I get a readystate:4 and bad request(400 status) error when I run the code, if I change the "POST" to "GET" it works.
This is not the first time I encounter this, but previously it has been in my spare time projects, this time it is for work. as mentioned above I can "solve" it by changing the method to "GET", but that is not the method you are supposed to use when you add to your database. I've tried to comment out the lines with "dataType", "contentType", and "processData", but it doesn't make a difference I still just get a bad request(400) error. I have several "GET"s that work fine elsewhere in functions.php and urlen is pointing directly to functions.php.
JS
function AddToTable(){
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
jQuery.ajax({
type: "POST",
url: urlen,
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(Data),
success: successfunction,
error: errorfunction,
});
function successfunction(data){
RefreshTable();
}
function errorfunction(data, status) {
alert("error: "+status+" Content: " + JSON.stringify(data));
};
}
Functions.php
<?php
function CreateProduct(){
exit;
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I expect it to send the data to the server function, so I can do more with it there. But I get a readystate:4 and state 400 errorcode.
UPDATED: to include the Functions.php part of the code.
I guess your data to be posted is malformed.
You have prepared it like
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
Variables to be posted should not be in quotes so your code there should begin like
Data={action:"CreateProduct",Password: Password.value,Varenr: Varenr.value, .....
and so on
A GET request to a URL will simply tell you whether or not it exists, in basic terms. If you send a GET request to cnn.com it will respond with a 200, if send a GET to cnnbootyshort.com, you will get no response.
In your case, rather than using exit, you could try using die(), along with an echo of what you want to send back to the browser.
<?php
function CreateProduct(){
echo "200";
die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
And your JS
function successfunction(data){
console.log(data); // for debugging
RefreshTable();
}
function errorfunction(data, status) {
console.log(data); // for debugging
alert("error: "+status+" Content: " + JSON.stringify(data));
};
Alternatively you can use wp_die() if you want to use a Wordpress specific function. Here is some documentation regarding its use.
<?php
function CreateProduct(){
wp_die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>

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',
}

Passing variables with URL not working quite right using PHP and ajax

I'm using AJAX to update a page every 5000 milliseconds. It works great but I have ran into one issue. When I try and get data that is in the URL using $_GET or $_POST it does not work. It instead returns a value of a 1. Here is some example code.
In main.php I have this:
$(document).ready(function worker() {
$.ajax({
url: 'Request.php',
type: 'POST',
success: function(data) {
$('#Live_data').html(data);
},
complete: function() {
setTimeout(worker, 5000);
}
});
})();
and when this is called it fires off the request.php. In request.php I have some code to grab what was added in the URL by a previous page but it dose not work. It goes something like this:
$value = $_get['test'];
This is supposed to return the value in the URL parameter test but it does not work.
Thanks!
You forgot to send data with the ajax query,
In this code, you can add GET data by append a query string to url value, or send POST data by setting data property of the request,
$.ajax({
url: 'Request.php?query=string&is=here',
type: 'POST',
data: {to: 'post', goes: 'here'},
success: function(data) {
$('#Live_data').html(data);
},
complete: function() {
setTimeout(worker, 5000);
}
});
see also https://api.jquery.com/jquery.post/#jQuery-post-settings
I've commented it as well but I'll post it as answer:
Change POST to GET in your jQuery AJAX request.
Use request.php instead of Request.php or the other way around.
Use $_GET instead of $_get. This variable is case sensitive.
Your not sending any data here. You can send the required data in Url or in Data Field.
url: 'Request.php?test=xyz',
or
data: data,

Getting php data from jQuery ajax without html forms

My idea is to write single page web application using jQuery and having server side in php, I want to do it without using html forms. So far I have this new.php file:
<?php
echo "Welcome";
?>
And javascript:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php',
success: function (data) {
alert('success' + data);
},
error: function(jqXHR,error, errorThrown) {
alert("Something went wrong " + errorThrown);
}
});
});
The alert i get is just "success" with nothing else.
I have apache web server running, and when i type same url in web browser it says "welcome".
Is this proper way to do server side since I'm not going to use forms?
Do I have to use some frameworks for that?
Try this:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php'
}).done(function(response){
var response = $.trim(response);
alert(response);
});
});
If you still get no reply from ajax, please verify your path (url: '....')
Also check your console for any errors...
One last thing: Ajax files should not always be accessible directly from browsers... You may want to consider protecting them (while they will still be reachable by xmlhttprequest:
<?php
//protect the file from un-auth access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
echo "Welcome";
?>
Of course in your particular "Welcome" case, that might not be necessary... I am just referring to more "sensitive" ajax files ;)
Old functions that I've did allows you to make a AJAX request to an URL also.
function Get(t,e,n){!function(){var s=new XMLHttpRequest;s.onreadystatechange=function(){4==s.readyState&&200==s.status?(e(s.responseText),s=void 0):s.status>=500&&(s=void 0,n(0))},t+=t.indexOf("?")>-1?"&tsmp="+Date.now():"?tsmp="+Date.now(),s.open("GET",t,!0),s.send()}()}
function Post(t,e,n,o){!function(){var s=new XMLHttpRequest;s.onreadystatechange=function(){4==s.readyState&&200==s.status?(n(s.responseText),s=void 0):s.status>=500&&(s=void 0,o(0))},t+=t.indexOf("?")>-1?"&tsmp="+Date.now():"?tsmp="+Date.now(),s.open("POST",t,!0),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),s.send(e)}()}
This is very simple to use... if you want to across the jQuery:
Get("http://localhost/pmfServer/new.php",function(msg){alert(msg)},function(err){alert("Error")})
This is to post data and after get:
Post("http://example.com/yourtext.php","wow=1",function(msg){alert(msg)},function(err){alert("Error")})
Also see if there are no errors in the console.
And... I recommend you to use encodeURIComponent when sending some string with user data.
encodeURIComponent("ÃÃO.. ! # # $ % Ohh! & %><")
Make sure your .html file beside the .php and change the url in javascript code to "new.php" as the following
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'new.php',
success: function (data) {
alert('success' + data);
},
error: function(jqXHR,error, errorThrown) {
alert("Something went wrong " + errorThrown);
}
});
});
I suggest to use framework for single page application such as http://durandaljs.com/

AJAX result OK but no data

I'm using jQuery to perform following AJAX request:
jQuery.ajax({
url: "url-to-script",
dataType: "html",
async: false,
success: function(data) {
console.log(data);
},
error:function(){
showMessage('Chyba', 'error');
}
});
Script that I'm calling is returning part of HTML. It is working properly.
But when I call this AJAX it will end with blank response in data. When I call it again it will return what it should and each next call is working. But the first one after page load is never working. I've no idea why.
I've also tried
if (data)
// do something
else
try again
But it just freeze my browser. So I don't know what is wrong.
Thanks for ideas!

Categories

Resources