I'm new to this community and a beginner with programming. I'm trying to post a JSON data with AJAX to another PHP file and my code is as follow:
--- AJAX code ---
<?php session_start(); ?>
//other codes in between
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//alert('Transaction completed by ' + details.payer.name.given_name);
alert(data.orderID);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
});
});
var orderid_data = data.orderID;
$.ajax({
url: "test_parse.php",
type: "POST",
data: {'order_ID': orderid_data },
success: function(data){
alert(data);
});
--- PHP code ---
var_export($_POST);
echo $_POST["order_ID"];
I've realised that my $_POST return an empty array.
Any help would be greatly appreciated :)
Since you open [...]test_parse.php directly in your browser, there is no POST-data present anymore, therefor its empty.
The POST-Data is part of the request. If you open it manually in the browser you perform a GET request.
What can you do to see the var_export?
You can use Chrome or Firefox for example both have Developer-Tools which allow you to trace the exact POST-Request you performed via ajax.
For Chome:
Hit F12 to open the Dev Tools
Navigate to Network
Now perform your Ajax-Post-Request and find it in the Network list. By clicking on the requests you will see all details you will need. Most Imporant for you is Response
Related
I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>
I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.
$(function() {
$( "#fenster" ).draggable({
stack: "#fenster", stop: function(event, ui){
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
$.ajax({
type: "POST",
contentType: "application/json",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
}
});
});
In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.
if((isset($_POST['x']))){
$_SESSION['xLoc'] = $_POST['x'];
echo "Test";
}
Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.
The PHP superglobal $_POST, is only available when you use these content types
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
You are using application/json which means you need to get the stream with...
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
$_SESSION['xLoc'] = $d['x'];
echo "Test";
}
Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.
$.ajax({
type: "POST",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server
I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.
Thank you all that took the time to help me, it's greatly appreciated.
I must create a simple app to:
create input with my variable (NIP)
connect to site https://wyszukiwarkaregon.stat.gov.pl
somehowe show in my app Captcha code from there and able to fill in and POST to above site
search there "NIP" POSTed from my app and show results
I tried to get content by cURL and JS but as we know there's Same Origin Policy protection... Posting by JSON ends the same.
Now I'm stuck and don't even know how to do it. Anybody have any ideas?
Thanks for any help how to can create it.
How about AJAX-Request via JQuery?
Links:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
dataType: "json",
url: "http://www.stat.gov.pl/regon/",
data: { name: "John", password: "XXXXX" }
})
.done(function( msg ) {
alert( "Your Response:" + msg );
});
I'm trying to get echoed variable from php and display on the console. I'm using jquery to send data and I know the backend php file script is working fine. Since I want to see the progress and the backend php script echo out the iteration number while the script is running, I'm trying to see how I can get the echoed variable with jquery and display on the console.
I've tried success, onloading but it doesn't seem to work. Any help would be very appreciated. Thank you!
EDIT
$.ajax({
url: location,
type: 'POST',
data:{
iteration:"10",
readsize:"200",
slimdepth:"3",
sourcedirectory:source,
packagepath:MP
},
dataType:'json',
success: function (response) {
console.log("SUCCESS!");
console.log(response);
},
onInteractive:function (response) {
console.log(response.responseText);
},
complete:function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log("Failure!");
console.log(response.responseText);
}
});
So this is how I send the data and backend php script gets the parameters without problems and it runs. Now I can't see anything until php is done running and then it echo everything. In the backend php script, I have iteration number that I want to check and that is the problem since I can't check while it is running but only it is done running.
From what I could understand from your question probably this is what you are looking for.
You are sending data to PHP file with jQuery post or send:
$.post(file.php, {post}, function(data){
});
If you want to log returned data from php in console you must use console.log() function:
$.post(file, {post}, function(data){
console.log(data)
});
and now data will be logged into browser console.
I must be missing something simple here. Firebug shows data being sent exactly as it should in NET tab (NET tab-> Post -> Parameters). PHP function will not even echo simple text.
The PHP:
add_action('wp_ajax_nopriv_process_json', 'process_json_received');
add_action('wp_ajax_process_json', 'process_json_received');
function process_json_received(){
echo "ANYTHING...";
exit;
}
The JS/Jquery (sending correctly)
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
$.ajax({ url: 'http://localhost:12345/site_name/wp-admin/admin-ajax.php',
data: {data: data},
type: 'post',
dataType: 'json',
success: function (response) {
alert("Got this from the server: " + response);
console.log( response );
$('body').append(response); // <-- Append the ajax response to the page body
},
complete: function(XMLHttpRequest, text_status) {
},
error: function (response) {
alert("Error getting php file");
}
});
Again, it doesn't matter what is in the PHP function, the response is always 0. It could be an "enqueue_scripts" thing but ajax request is sending exactly as it should. NET tab in Firebug shows perfect json data so the problem has to be with the PHP function (or correct access to it). Maybe Wordpress is somehow blocking it??? Has to be something simple - I'm hoping a fresh set of eyes will help. Thanks in advance...
Because ANYTHING... isn't correct json format. Try echo json_encode(array('msg' => 'test')); This causes that JQuery have a parsing error (not error from receive)
Change the line in javascript from
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
to
var data = { action: 'process_json', value_name: 'value' };
Wordpress expect POST Data so it can read $_POST['action], you should never Stringify it, but use core javascript object only.
Read more about it : http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
EDIT:
Also change data: {data: data}, to data: data,
:) I miss that last time.
OK, I got it using the following code:
In main PHP plugin file:
echo "<script src='URL PATH TO/ajax_file.js' type='text/javascript'></script>";
add_action( 'wp_ajax_foobar', 'foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'foobar_handler' );
function foobar_handler() {
// Handle request then generate response
echo "ANYTHING..."; // do stuff here
die(); // avoids extra 0 at the end of the response
}
In ajax_file.js: (referred to above in script tag)
jQuery(document).ready(function($) {
$('#id_to_submit_button').click( function() {
var data = {
action : 'foobar',
Whatever : '1234',
}
;
// ajaxurl only needed for front - facing public pages, comment out for back end pages
var ajaxurl = 'http://SITE_URL/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
}
);
}
);
}
);
As soon as I included the script in this way it worked, it would not when placed in a PHP function as many sources suggest. I tried soooo many other ways that should have worked. I went step by step on the Wordpress codex pages (many times) and several other tutorials. Enqueueing scripts, registering scripts, following all recommended practices. I still don't understand why this way works for me and all the other "correct" ways didn't. Could be something in my local server environment. Big thanks to those who answered and tried to help. God knows I have gotten the quick answer on StackOverflow enough times, I hope this saves someone the long hours I spent testing and troubleshooting...