Php-Ajax-JS Multiple Data Returns Problem - javascript

i have a problem.I am waiting for your help.Thank you
index codes are here.Even if i write dataType:JSON it didn't work.
index.php
function referansButon(sayfaNo)
{
$.ajax({
url:"ajax.php",
type:"POST",
data:"action=referansButon&referansSayfano="+sayfaNo,
success:function(data)
{
var result=$.parseJSON(data);
alert(result[0]);
alert(result["referanslar"]); // i know they are the same but i just wanted to see it if it
//is working
}
});
}
ajax.php
$referanslar="sdfdsfds";
$sayfalar= "sdfsdfdsfds"; //just for trying values.
$array=array("referanslar"=>$referanslar,"sayfalar"=>$sayfalar);
echo json_encode($array);

data is a string which is returning from $.ajax you convert the string to json and store in var result and after that you are using data again which is still string. update your code
var result=$.parseJSON(data);
and for first obj
alert(result.referanslar);
And for second obj
alert(result.sayfalar);
instead of [0] & [1]

Related

Javascript : Get data through ajax call

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

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

parsing JSON inside of ajax sucess function

I am trying to parse and display this JSON data that gets returned. Basically I have an ajax call which reads an input, sends it via POST to a PHP page and the php page var_dump's the array which contains the data.
array(1) {
[0]=>
string(21) "jsmith#yahoo.com"
}
My AJAX Call looks like..
<script>
function searchDB()
{
var lookupemail = $('#lookupemail').val();
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: {wordpress: lookupemail},
success: function(server_response)
{
var response = server.response.1;
alert(response);
}
});
}
</script>
How do I retrieve the string that is returned and assign it to a javascript variable?
Your PHP code would have to output JSON in the first place:
$array = array('jsmith#yahoo.com');
echo json_encode($array);
To make it into an array in JavaScript you can use
var newArray = $.map(server_response, function(el) { return el; });
However, you can access the JSON directly using the json_encode in PHP.
json_encode($phparray);
and then...
server_response.arraykey

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.

Categories