Ajax data parse - javascript

I have a page with comments. By ajax, send a request to php page by. Php then scans the database... In general the standard logical operations. In any case, I meet php
echo '<script>show_info("my_text")</script>';
(show_info - js function which toggle info div and it displays my text).
And if all is well DB will transmit
echo 'ok';
My ajax success
success: function (data) {
if (data == "ok") {
document.write ("It's work!");
};
}
But unfortunately it does not work.
Maybe it is necessary somehow break the data into two parts, script and other text.

You're sending out the response straight away to the server with echo '<script>show_info("my_text")</script>'; as a response. because of this, data won't evaluate to 'ok'.
Instead, you should send back an array:
$ret = array(
'script' => 'show_info("my_text")',
'status' => 'ok'
);
echo json_encode($ret); // <--this should be done after all processing
Then in the ajax function you need to add the dataType parameter
$.ajax({
//etc
dataType: 'json',
success: function(data){
if(data.status == 'ok'){
eval(data.script);
}
}
});

Related

How to get response from PHP server asynchronously

First of all I know that there are many questions already regarding this.After reading all answers and trying it out ..but none of them worked.So I'm uploading a question here.Please don't delete it.
So,I created a html file with a form and then sent the form data using ajax jQuery to PHP file as follows.
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata
});
//display the message sent by PHP
/*Use the data sent by PHP to perform
different function*/
Now I want PHP to send a message to js or html or anything else.Also, I want PHP to send some Boolean data which I will be using to perform some function.
If you want to send multiple data then you can do this by using array and send them json encoded and you will receive data in "success" callback function of ajax call
consider below example
ajax call
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata,
async: true,
dataType: 'json',
success: function(data) {
console.log(data); // check result in console
$('#result').html((data.content) ? (data.content) : '???');
$('#result').prop('title', data.title);
$('#jsonstring').html('Json object: '+JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
<?php
$result = array(
'title' => 'Title',
'status' => 0,
);
echo json_encode($result);
?>
You can use the powerful pure javascript browser native fetch api.
To retrieve text/html.
fetch("https://api.github.com/")
.then(function(response) { return response.text() })
.then(function(text) {
console.log(text)
})
To retrieve json.
fetch("https://www.reddit.com/.json").then(v => v.json()).then((function(v){
syn = JSON.stringify(v)
main.innerHTML += syn
})
)
<div id="main">
Server side the base of a json api would be:
if ($_GET["myapi"] != ""){
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode(["Hello","World"]);
exit;
}
Calling: mysite/?myapi=whatever
Output: ["Hello","World"], with a json header, and CORS enabled.
Learn more about javascript promise(s)

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Categories

Resources