Getting php data from jQuery ajax without html forms - javascript

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/

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');
?>

Using Ajax to run php function

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");
}
});
});
});

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>";
}

$.post is not working (anywhere)! Why?

My calls to $.post are not working all over my code. I'm not sending the request to other domains and, actually, I'm doing everything localhosted. My localhost alias was automatically defined by the Mac OS X 10.8 as ramon.local and I'm requesting from http://ramon.local/linkebuy_0.7/resourceX to http://ramon.local/linkebuy_0.7/resourceY. There are no errors on Chrome's console.
The server side doesn't receive the request and I can check it by accessing directly from the browser (typing the URL).
It's not just one call that is not working, none of them are. They were all working days ago and I'm suspicious that I accidentally changed something on my local settings. What could it be?
Here's an example of what I'm facing:
$.post(
<<CORRECT URL INSIDE THE DOMAIN>>,
{},
function(response) {
console.log('THIS SHOULD BE PRINTED ON CONSOLE');
alert('THIS SHOULD BE POPPED UP');
}
);
I don't get the alert, neither the console message while running the code above. So I tried the following:
$.support.cors = true;
$.ajax({
url: "http://ramon.local/linkebuy_0.7",
dataType: "json",
type: "GET",
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
alert(error + " - " + status);
}
});
I just came with $.support.cors = true; and crossDomain: true to check if it was a cross domain issue. So I was alerted No Transport - error same way as before.
What can I do to solve that?
Thanks in advance.
Try this and see if you are getting any alert:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("your url", function() {
alert("success");
}).success(function() {
alert("second success");
}).error(function() {
alert("error");
}).complete(function() {
alert("complete");
});
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
alert("second complete");
});​
Well, I solved the problem in a very strange way.
I deleted the JQuery file and downloaded it again, replacing the old one. Happens it worked out.
So, if you're:
Making AJAX requests that are not cross-domain;
Using JQuery for it (e.g. $.post, $.get, etc);
Getting No Transport AJAX error
Then re-download and replace you're JQuery source.
Else, if you're making cross-domain requests (not this case), then look for JSONP and try to set $.support.cors = true; at the beginning of you're code.
Thanks everyone for the comments and answers.

Download JSON file via JavaScript/JQuery - HTTP-Status Ok - JQuery Error

I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.
Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests
Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}
Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});
If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.

Categories

Resources