Javascript : Get data through ajax call - javascript

It may be possible this question has been posted so many times.But i didn't get answer from those one.I have passed url in Ajax call and i want whatever i'm getting from database through the query,get in success method of ajax request.But somehow i didn't get this.
Ajax call method:
function validateAmount() {
var amount = document.getElementById("amount").value;
// alert(amount);
// var y = x.value;
$.ajax({
url : "{{url('getAmount')}}",
type : "GET",
async : false,
dataType : "json",
success : function (result) {
alert();
}
});
}
and database query:
And this is what i want to return
public function getAmount(){
$user_id = session('user_id');
$res = DB::table('table_name')->where(['user_id'=>$user_id])->first();
return $res;
}
And one more thing,when i simply echo string in getAmount method ,ajax call get succeed but when i try to access the data through query,i'm getting fail.
Please help me to get this.
Any help will be appreciated.Thanks in advance.

First : Remove the async: false as Rory mentioned in the comments.
Second: For the ajax you have to use the echo json_encode($my_data_array);
Third: Dont use alert rather use console.log(result) to view your data.

Use Collection::toJson() method to transform you collection to json string:
$res = DB::table('table_name')->where('user_id', $user_id)->first();
return $res->toJson();
Collection::toArray() works too

Related

How to properly get a parameter send using ajax in a Symfony controller (annotation)?

I have been struggling for the past 2 days and none of the answer I've find so far on the internet have helped me so far.
I'm trying to pass data using ajax on a symfony project. The goal is to update a twig value .
So i've set an ajax call like this :
$searchbar = $("#searchBar");
var btnSearch = document.getElementById("btnRecherche");
btnSearch.onclick = chargeClientsData;
function chargeClientsData()
{
let searchVal = $("#searchBar").val();
console.log(searchVal);
$.ajax({
url: "{{ path('showIt') }}", // point to server-side PHP script
dataType: 'json',
data: {data : searchVal },
type: 'POST',
success: function(data){
console.log(data);
$('#monelement').html("test");
}
});
}
And I'm tring to get if using this controler :
/**
* #route("/showIt}", name="showIt", methods="POST")
* #param $request
* #return Response
*/
public function showIt(Request $request){
var_dump($request);
if($request->isXmlHttpRequest()){
$search = $request->query->get('data');
var_dump($search);
$response = $this->checkValidRequest($request);
return $response->setData(['search' => $search ]); // working
}
$response = $this->checkValidRequest($request);
$response->setStatusCode(500);
return $response;
}
The var_dump($request) show none of the value, and of course var_dump($search) come as NULL.
In twig, $("#searchBar"); send the righ value, and I do get a success but with null values
Is there something that I did wrong ?
Thank for the help !
Since you are using a POST request, you can get the your POST parameter in your controller like this:
$search = $request->request->get('data');
instead of
$search = $request->query->get('data');
that you are currently using. Note that $request->query->get('data') is used for GET method.

Sending JSON to PHP using ajax, troubles with data

my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic

Check return value when parsing json array in javascript

I'm a beginner in ajax and json so I'm sorry if this question is a bit stupid. I'm retrieving the data(city id and name) and put them in an array then use json_encode. Then I call the getCities function but I'm not sure if I'm getting the correct cities. I tried using document.write but there's no output. How can I know if I'm getting the correct ones? Thank you for your help.
Here's the getCities.php:
$json = array();
$query = "SELECT cityID, cityName FROM city";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$coord = array('id' => $row['cityID'],'city' => $row['cityName']);
array_push($json, $coord);
}
$jsonstring = json_encode($json);
And here's the javascript part:
function getCities(){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json'
}).responseText;
return JSON.parse(string);
}
$(document).ready(function (){
var city = getCities();
while (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
There are 2 easy ways to do this. First of all I use Google Chrome (or Firefox) to facilitate testing. Look at the docs and you will see that your $.ajax call will also accept a success function. You could put it in the ajax call under dataType like this:
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success: function(data) {
console.log(data);
}
});
string.done();
Notice how I changed the end of the ajax call. It is now saying, when this call is done, call the success function. You can also put an error function in the ajax call if you want to have something print out in case of an error. The success function will then be called when the data returns. It will print in the console of your Chrome debugger. Google that term to find out how to show it, super easy stuff. You can also put a break point on the console.log function call (Google how to do that also) and you will be able to inspect the object that is returning from your ajax call.
Also, the console.log will not work in IE as far as I know.
Have fun.
function getCities(callback){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success:callback
});
}
$(document).ready(function (){
getCities(function(data){
console.log(data);
var city = JSON.parse(data);
if (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
});
Ajax is asyn, you cannot use var city = getCities();. Because when you call that, ajax response has not arrived yet. You need to pass in a callback function, and when ajax response has arrived, call that function to get the response.

Creating a variable from returned data ajax post

I want the data returned from an ajax post to be put into a javascript variable where I can then run an if statement checking whether that variable is equal to true. However, Firebug is telling me the variable verify is not defined. How do I write the function within the ajax post to set the data to verify correctly? Code is below.
$.post('ajax_file.php',
{
user_id: user_id,
band_term: band_term
}, function (data) {
var verify = data;
if (verify == 'true')
{
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}});
The ajax file returns true on success and false on failure.
if (mysql_query($sql) == true)
{ echo 'true';} else {echo 'false';}
Firebug shows me that the ajax file is returning with the string true, so I know the ajax file is working.
The issue is on a few places.
First, how you output data on you .php file. You should be returning JSON and accepting JSON on you ajax request. Look at this example:
<?php
$variable = array("stat" => true, "data" => array(10, 10));
print_r(JSON_Encode($variable));
?>
That will output this:
{"stat":true,"data":[10,10]}
Then on yout JS you'd do:
$.post('ajax_file.php', {
user_id: user_id,
band_term: band_term
}, function (data) {
//Data is the whole object that was on the response. Since it's a JSON string, you need to parse it back to an object.
data = JSON.parse(data);
if (data.stat === true){
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}
});
It's because verify was created in the callback function. Also, that variable isn't visible outside that function.
To operate on returned data from an AJAX call, do it in the callback function.
$.post('ajax.php', {
user_id: user_id,
term: term
}, function (data) {
var verify = data; //assuming data is just true or false
if (verify === 'true') {
unnecessary code
}
});
The variable is defined inside the callback function is does not match the scope of the document.
To make it actually work, just define it anywhere in the beginning of your script as follows:
var verify;
$.post('ajax.php',
{
user_id: user_id,
term: term
},
function (data)
{
verify = data; // then also remove the word var from your code here.
if (verify == 'true')
{unnecessary code}
}
);
-i wouldn not use j query for ajax ( i find getdata to be better but the call back variable needs to be passed to the next function
ie. if you are gonna alert(data) as your call back, do your if statements there.
also i was running into similar problems. using numbers such as one or zero in my php response helped alot, and i just used js to determine what the actual string or alert output would be

How to get the type of the returned object from .POST ajax call?

Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {
if (output == "true"){
and here is the php script that being called
include_once('class.MySQL.php');
$userid = $_POST['action'];
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true
Thanks in advance!
Trying to parse the type of an ajax response tends to be super unreliable, in my experience.
For that reason, I (now) make darn sure that whenever I write a server side function that is meant for returning ajax data, I keep it perfectly in line with my own set response "standard", and then set my response type in the ajax method to JSON.
Doing so makes handling errors much more predictable.
An example of a standardized response would be:
$ajaxResponse = array(
'data' => $someData,
'result' => true,
'message' => 'your yadayada was succesful',
'timestamp' => time()
);
print json_encode($ajaxResponse);
and in ajax, your response would be like:
success: function( response ) {
if(response.result) {
alert(response.message);
}
}
Sorry if this isn't much help but you could try:
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
dataType: 'json',
success: function(output) {
if (output) { ... }
and
echo json_encode(true);
// echo json_encode($sharing);
The jQuery documentation gives more detail on what this call returns: http://api.jquery.com/jQuery.ajax/.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery
1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
It looks like you are expecting the data that is returned from the AJAX call to be the string "true" in your test, so if that isn't passing it must be you are getting back something other than this exact string.
I recommend using the net tab of Firebug in Firefox to see the XHR request and to examine the response of what you are getting back to see if it is something other than what you expect.

Categories