What is the right way of sending a var on AJAX - javascript

I have a javascript function that calls a Webmethod. I tried sending a regular string to the webmethod and it works. On var empid= $('#' + txtId).val() Im getting the right value of the text box. What is the right way of sending empid over ajax ? I have tried a few thing and they dont work. Any help would be appreciated. Thanks
.js
function toggle(txtId, lblname, txtcode) {
var empid = $('#' + txtId ).val();
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{ id: empid }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).html(data.d);
}
});
}
.asmx.vb (webmethod)
Public Function GetEmployeeName(ByVal id As String) As String
Return "It works"
End Function
This is a screen shoot when removing contentType

Instead of
data: '{ id: empid }',
use
data: { id: empid },
Its sending JSON

Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>

You can use like below:
var empid=$('#txtEmpId').val();
Pass empid in data as
data: { id: empid },
Check out the fiddle here: http://jsfiddle.net/gN6CT/103/

Related

How to get return text from php file with ajax?

I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).
How can I get "hello" returned from the php file to my javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
The PHP file:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
You can change the code inside PHP like this
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
Then, change your ajax call
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.
There are two changes to be done:
Change the type to "GET" since you directly call the PHP File.
remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});

ajax method post send to mysql query

I pass the variable javascript method by ajax post method to the php file in this way:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: 'php/file.php',
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
name: name,
time: time
},
success: function(response){
console.log(response);
}
});
});
Request Payload in my Browser returns: name=Adrian&time=00%3A01%3A59. What should I write in the file file.php to send variables using sql query to my mysql database?
You can make good use of php explode() method here:
$string = name=Adrian&time=00%3A01%3A59
$parameters = explode("&", name=Adrian&time=00%3A01%3A59)
This will give you an array $parameters:
($parameters[0] == name=Adrian,
$parameters[1] == time=00%3A01%3A59)
Now you can get the name and time from $parameters:
$name = explode("=", $parameters[0])[1];
$time = explode("=", $parameters[1])[1];

jquery ajax not posting any data on codeigniter

hy please help me i working on ajax but when i var_dump the data it seem empty
object(stdClass)#20 (0) { }
$.ajax({
url: base_url+"process_redeem_check",
data: $("#formId").serializeArray(),
type: "POST",
dataType: "json",
contentType: "application/json",
thats is my javascript code
public function process_redeem_check()
{
$input = (object) $this->input->post();
$check = $this->gemstone_model->redeem_check($input);
if ($check->success === TRUE) {
echo json_encode(array('status'=>true));
} else {
echo json_encode(array('status'=>false));
}
}
that my controller please help me i done searching all day
To use $this->input->post() initialize the form helper. You could do that by default in config folder's autoload.php.
include form in the the array.
$autoload['helper'] = array('form');
and use .serialize() instead of serializeArray()
$.ajax({
url: base_url+"process_redeem_check",
data: $("#formId").serialize(),
type: "POST",
dataType: "json",
contentType: "application/json",
And then check you datas your are getting or not
public function process_redeem_check()
{
$input = $this->input->post();
print_r($input);exit;
}

UNDEFINED - multiple return values from PHP with jQuery AJAX

Because I get undefined. Where I am failing?
Code:
function add(id,cost){
var info = {
"id" : id,
"cost": cost,
};
$.ajax({
data: info,
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});
}
archive a.php
PHP:
$cost=$_POST['id']*$_POST['cost'] + 137;
echo json_encode(array("r1" =>$_POST['id'], "r2" => $cost));
Why do you think $.ajax will understand datos as a JSON? You need to specify it, you can do it using several ways.
Parsing it
success: function (datos) {
datos = JSON.parse(datos);
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
Specifying in $.ajax itself
$.ajax({
data: info,
url: 'a.php',
type: 'post',
dataType:"json",
....
Setting header in PHP (doesn't work for < IE8)
header('Content-Type: application/json');
I would suggest you to use a combination of first one and third one. Lets not leave any stone unturned.
Datos is probably a string
You can do:
datos = JSON.parse( datos );
Or, you can set the return type to JSON:
$.ajax({
data: info,
dataType: 'json',
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});

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);
}

Categories