First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.
Related
I have used before these jquery-ajax and php codes. Everything was fine but know there is a problem that success function not working. However, php codes are working, I can add data to mysql database, but I couldn't post info back to javascript file again by use "echo" or any way. Is this problem could originate because of server? I need your support.
I have checked php file is working or not and there was no problem about php. In javascript file in ajax codes, I have tried beforeSend and complete functions, everything were fine. But success function not working.
JS codes:
var userCookie = 1;
var question_txt = document.getElementById("question_txt").value;
var category_slct = document.getElementById("category_slct").value;
$.ajax({
type: "POST",
url: websitePHP + "ask.php",
data: {
user : userCookie,
quest : question_txt,
cat : category_slct
},
beforeSend: function(){
},
success: function(data){
alert(data);
if(data == 'ok'){
alert('Question added');
}
}
})
PHP codes:
include("ayar.php");
$userID = $_POST['user'];
$categoryID = $_POST['cat'];
$question_txt = $_POST['quest'];
$askedTime = time();
$addQuestion = $vt->prepare("INSERT INTO ".$QUESTIONS." (userID, categoryID, question, image, link, sight, pinned, bestAnswerID, askedTime, publishedTime, published)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$addQuestion->execute(array(''.$userID.'',''.$categoryID.'', ''.$question_txt.'', '', '', 0, 0, '', ''.$askedTime.'', '', 0));
echo 'ok';
exit();
I need to get back response from php to js by success function in ajax.
Thanks for your help,
Best regards.
Can you try
return 'ok'; instead of echo 'ok'; and removing exit(); function
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
From everything I've read on the internet, the way of returning HTML, JSON, etc., from a PHP script is simply by echoing it. I can't get it to work, however.
My JS is
jQuery('#new-member').submit(
function()
{
var formUrl = jQuery(this).attr('action');
var formMethod = jQuery(this).attr('method');
var postData = jQuery(this).serializeArray();
console.log(postData); // test for now
jQuery.ajax(
{
url: formUrl,
type: formMethod,
dataType: 'json',
data: postData,
success: function(retmsg)
{
alert(retmsg); // test for now
},
error: function()
{
alert("error"); // test for now
}
}
);
return false;
}
);
and I've verified that it is correctly calling my PHP script, which as a test is simply
<?php
echo "Yo, dawg.";
?>
but all that does is open "Yo, dawg." in a new page. The expected behavior is for it to alert that message on the same page I was on. What am I missing here?
Hi Guys I have the following function that is called on a link:onclick(), but for some reason the $.ajax does nothing at all - have even stripped my php code to only dump the $_POST var but I still get no feedback from the function - all i get is the alert msg - which is also just there for test purposes...
called there:
Save
function saveMyGame(){
var usern = $('#usern').attr('value');
var usrPoints = $('#userPoints').attr('value');
var usrLevel = $('#userlevel').attr('value');
var saveState = this.imgPath;
alert('Saving your game: '+usern+' Points: '+usrPoints+' Level: '+usrLevel+' state phase: '+saveState);
e.preventDefault();
var svGame = {act:'saveGame',user:usern, Points:usrPoints, Level:usrLevel, saveGState:saveState} ;
$.ajax({
url: "game/lib/updateGame.php",
type: "POST",
cache: false,
data: svGame,
dataType: "html",
success: function(svGame) {
$(".traget").html(svGame).fadeIn('slow');
}
});
}
the PHP code is suppose to check act, then verify that all required info is passed, than process the request or display an error msg...
<?php
if(isset($_POST['act']) && $_POST['act'] == 'saveGame') {
//Process save game request
/*if(isset($_POST['user']) && isset($_POST['userPoints']) && isset($_POST['userLevel']) && isset($_POST['saveGState']) ) {
$Game->saveGame();
echo'<br>....'.$_POST['user'];
} else {
echo 'Please provide correct information for saving...';
}
*/
echo var_dump($_POST);
}
Url in your ajax request has relative path url: "game/lib/updateGame.php", without slash in the beginning of the url like url: "/game/lib/updateGame.php",.
So maybe if your page adress differ from root (for example http://yourdomain.com/games/), full path will be http://yourdomain.com/games/game/lib/updateGame.php and therefore the server method is not performed.
Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);