Pass variable via ajax to api.php - javascript

I am trying to pass a js variable via ajax to the php side. My js code is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var sAgentId = 'hi'
$.ajax({
url: "api-test.php",
method: "POST",
data : { id:sAgentId}
}).done(function(){
console.log('done')
})
and in the php file, I am trying to get the variable via post:
$sAgentId = $_POST['id'];
But finally in api i get the notification that says
Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2
Can anyone tell me what I am doing wrong?

Try adding this to your AJAX method:
dataType: "json"
Try also console logging the response back to check $_POST['id'] is being set.
.done(function(data) {
console.log("Data: ", data);
});
and in your PHP just return $_POST['id']

var sAgentId = 'hi'
$.ajax({
url:'api-test.php',
type: "POST",
data: {id: sAgentId },
cache: !0,
dataType: 'json',
success: function(data) {
console.log(data);
}
});

try replace method by type:
type: "POST",

Related

Send Request In Laravel Using AJAX GET Method

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

Complete JSON being outputed

The output consists of the complete JSON, which is:
{reply:"Login success"}
The expected output is only the value for the key 'reply' ,
Login success
The required code:
HTML
<div id="resp" style="color:red;"></div>
JS AJAX JQUERY
$.ajax({
url: 'tt.php',
method: 'POST',
data: {'pass': pass , 'uname':uname},
success: function(data) {
document.getElementById("resp").innerHTML = data;
}
});
PHP
$data['reply'] = "Login Success";
echo json_encode($data);
Solutions tried to print the necessary data
data[0]
data[1]
data[reply]
data.reply
data["reply"]
The PHP code you show us is not outputting what you say your expected output should be but, you can tell the AJAX call to expect JSON to be returned by adding dataType: 'JSON', to the properties of the call.
Then you can address the reply as data.reply
$.ajax({
url: 'tt.php',
method: 'POST',
dataType: 'JSON', // added this line
data: {'pass': pass , 'uname':uname},
success: function(data) {
// then you can address the reply like this
document.getElementById("resp").innerHTML = data.reply;
}
});

Ajax call not sending to POST

I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}

Populate a html div with json data received from a server

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

Can I send the value of html like this $("#id").html() to code behind?

I have already tried it via ajax but it doesn't work so Help me please !!!!!!
And i tried it into cookie but in code behind didnt see it
var datah = $(“#currid”).html()
var data = {
id: currid,
html: datah
};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(msg){
alert( "return back" );
}
});
Try this
You must encode the html content before transmitting . You can use escape in java script for this.And you can decode back it from server
var encodedData= escape($(“#id”).html()) ;
var postData = { htmlData:encodedData};
$.ajax({
type: "POST",
url: url,
data: postData,
success: function(msg){
// do your operation
}
});

Categories