How to get the PHP var after Jquery $.ajax - javascript

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax

You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.

Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});

Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Related

php sending values to ajax faild error

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});

checking JSON data with jQuery

I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

How to pass data using jQuery/ Ajax to a URL

How to pass the fetched data using $.get() from a URL to a particular URL with query_string that can be retrieved using $_GET() in PHP. I'm using following but not working. I want to pass the fetched data into following parameter http://example.com/data?data=FETECHED_DATA
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get( "http://ipinfo.io/'.$ip_address.'/org", function( data ) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: data,
success: success,
dataType: dataType
});
});
</script>';?>
Well, don't recommended PHP to fetch and send data
I believe this will do what you want
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get("http://ipinfo.io/'.$ip_address.'/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: success,
dataType: dataType
});
});
</script>';?>
the only change is data: data changed to data: {data: data}
that's a lot of data :p
see this cut down mock up, http://jsfiddle.net/cm8o5dk8/ if you have a decent browser that can show you the network "usage" you'll see that the mockup fails trying to GET http://example.com/data?data=AS15169+Google+Inc.%0A - the %0A comes back from ipinfo.io
Thanks it worked
$.get("http://ipinfo.io/8.8.8.8/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: function() {},
dataType: 'json'
});
});

Post array from javascript to php function using Ajax

i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :
<script>
function send(){
var obj = JSON.stringify(array);
window.location.href = "post.php?q=" + obj;
}
</script>
i was try, but still fail. really need help..
As described in the JQuery API documentation, you can use
var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
url: urlWS,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function(result) {
// do something here with returned result
}
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';
$.ajax({
url: 'http://something.com/post.php',
data: {array: array},
type: 'POST'
});
try like this,
var data_to_send = $.serialize(array);
$.ajax({
type: "POST",
url: 'post.php',
data: data_to_send,
success: function(msg){
}
});
or
you can pass as json like below,
$.ajax({
type: "POST",
url: 'post.php',
dataType: "json",
data: {result:JSON.stringify(array)},
success: function(msg){
}
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
url:"post.php"
type: "POST",
data: {dataarr: arr},
complete: function (jqXHR, textStatus) {
}
You can try this .this will work
example
ajax code:
$.ajax({
url: 'save.php',
data: {data: yourdata},
type: 'POST',
dataType: 'json', // you will get return json data
success:function(result){
// to do result from php file
}
});
PHP Code:
$data['something'] = "value";
echo json_encode($data);

Categories

Resources