Why php ajax is not giving any response? [duplicate] - javascript

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I am working on my college project, In that i have a webpage which is supposed to display City and temperature, I am trying to use AJAX to update temperature at some intervals.
Here's the code
for ajax request Java Script, I saw this code in this answer https://stackoverflow.com/a/18243161/4341530
function postAjaxRequest(qry){
alert("Ajax response on " +qry);
$.ajax({
type: "POST",
url: "ajax_resp.php",
data: {q: qry},
dataType:'JSON',
success: function(response){
dispatchCallBack(qry,response);
}});}
the alert("Ajax response on " +qry); is working fine so I know this code is running. But when I put this kind of "alert()" just before dispatchCallBack(qry,response); its not working, so I infer here that the request is not successful.
Here's ajax_resp.php
<?php
if(isset($_POST['q'])&&!empty($_POST['q'])
{
if($_POST['q']=="c_temp")
{
$api_key = "Here's my api key, working alright";
$city_id = "here's city id, also working correct";
$url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
$json = file_get_contents($url);
$json_o = json_decode($json);
$city_name = $json_o->city->name;
$temp_c = $json_o->list[0]->main->temp-273;
echo json_encode(array("city"=>$city_name,"temp"=>$temp));
//I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
}
}?>
so I can't figure out what's wrong. I am newbie :p May be some silly mistake, would be greatfull if pointed out.

Please look at the code below and correct them
[1] use single quotes or double quotes to get data from $_POST variable having the string index
[2] $qry is not defined earlier. After reading the question the most probable value of the $qry can be $_POST['q']. So replace $qry with $_POST['q'] or assign $qry = $_POST['q']
if(isset($_POST['q'])&&!empty($_POST['q'])
{
if($_POST['q']=="c_temp") <== $_POST['q'] instead of $qry
{
$api_key = "Here's my api key, working alright";
$city_id = "here's city id, also working correct";
$url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
$json = file_get_contents($url);
$json_o = json_decode($json);
$city_name = $json_o->city->name;
$temp_c = $json_o->list[0]->main->temp-273;
echo json_encode(array("city"=>$city_name,"temp"=>$temp));
//I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
}
}?>

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

I know why I am getting unexpected { token but I don't know how to fix it when my php needs to send collection of datas to javascript

I am using this javascript fetch code to get data from php
async sendRequest(selectValue=this.selectValue){
const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue);
const fetchJSON = await fetchResponse.json();
await console.log(fetchJSON);
}
this is php code which communicates with MYSQL and sends data to javascript
<?php
header('Content-Type: application/json');
include 'db/db_connection.php';
$mysqli = new mysqli('localhost','root','','worddb');
if(connectDB($mysqli)){
$mysqliQuery = "SELECT * FROM wordlist ORDER BY wordIndex DESC LIMIT ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($mysqliQuery)){
print "Failed to prepare statement\n";
}else{
$stmt->bind_param("i", $_GET['select']);
$stmt->execute();
$result = $stmt->get_result();
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
}
}
?>
and this php returns
{"wordIndex":94,"english":"seemingly","korean":"\uc678\uacac\uc0c1\uc73c\ub85c,
\uac89\ubcf4\uae30\uc5d0\ub294","swedish":"till synes","synonyms":"apparently","example":"Seemingly,
he borrowed the money from the bank"}
{"wordIndex":93,"english":"evade","korean":"\ud53c\ud558\ub2e4,
\ud68c\ud53c\ud558\ub2e4","swedish":"undvika","synonyms":"elude, evoid","example":"He is using the
same tactics of distract and evade as the Chancellor used during his speech"}
{"wordIndex":92,"english":"eclipse","korean":"\uac00\ub9ac\ub2e4, \ube5b\uc744
\uc783\uc74c","swedish":"f\u00f6rm\u00f6rka","synonyms":"blocking, beating","example":"Her work was
in eclipse for most of the 20th century"}
{"wordIndex":91,"english":"impede","korean":"\uc9c0\uc5f0\uc2dc\ud0a4\ub2e4",
"swedish":"f\u00f6rhindra","synonyms":"delay, hinder","example":"This will impede learning,
essentially causing more problems than solutions"}
{"wordIndex":90,"english":"exposure","korean":"\uc704\ud5d8\uc5d0 \ub178\ucd9c,
\ud3ed\ub85c","swedish":"exponering","synonyms":"subjection, uncovering","example":"God knows you
probably saved my life, at least from exposure or pneumonia"}
I know it shows unexpected token { because php is returning multiple json object because
when I did echo just one json object it works fine.
$resultJSON;
foreach($result as $resultArray){
$resultJSON =json_encode($resultArray);
}
echo($resultJSON);
but my php needs to send all items ,but I don't know how to do that because console shows unexpected token {}
I read this post before posting my question
Why am I getting unexpected '}'?
but solution in this post was to add semicolon, but I have semicolons in my code..
Transform your results in an array :
$resultJSON = array();
foreach($result as $resultArray){
$resultJSON[] = $resultArray;
}
Then output the array :
echo json_encode($resultJSON);
It goes wrong here:
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
You output:
echo json1;
echo json2;
echo json3;
However, on the clientside the output is collected and treated as one json. So javascript will work with json1json2json3. And that's not a valid json.
If you don't have to do anything else then sending the result back
echo json_encode($result);
would do.

Send email with data retrieved from an ajax request [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to retrieve information from text fields on button click and send the data to mail#example.com:
$(document).ready(function() {
$("#submit").click(function() {
var email = $("#email").val();
var name = $("#Name").val();
var subject = $("#Subject").val();
var text = $("#textarea").val();
var telephone = $("#tel").val();
var varData = "email : " + email + "name : " + name + "subject : " + subject + "text : " + text + "telephone : " + telephone;
console.log(varData);
$.ajax({
type: "POST",
url: 'sendPHP.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
sendPHP.php:
<?php
$to = 'mail#example.com';
$name = $_POST['email'];
and so on ..
..
..
mail(mail#example.com, name, (here goes email, name, subject, textarea, tel) as message in new lines);
and somewhere i have to write from what emial im sending to example#gmail.com and what is it's password i guess
?>
While it is still somewhat unclear what your exact concern is, I have a few thoughts on your process.
1 - You are sending data to a php file as a string which is not recommended and is probably giving you problems right there. I have really seen 2 approaches to sending data to the server via post: A) store your data in a form and use jQuery's $().serialize() function, or B) store your data in a JSON object and send it that way.
Option B is my preferred method because JSON simplifies everything. It has the advantage that your data is already stored as key/value pairs, and PHP makes it super easy to work with JSON using the json_decode function. Let's make a few changes to the existing code you have:
$(document).ready(function() {
$("#submit").click(function() {
var email = $("#email").val();
var name = $("#Name").val();
var subject = $("#Subject").val();
var text = $("#textarea").val();
var telephone = $("#tel").val();
var varData = {
"email" : email ,
"name" : name,
"subject" : subject,
"text" : text ,
"telephone" : telephone
} //This is your data in JSON form
console.log(varData);
$.ajax({
type: "POST",
url: 'sendPHP.php',
data: JSON.stringifiy(varData), //Notice that I added JSON.stringify
success: function() {
alert("message sent");
}
});
});
});
Now I'll show you how to handle this in PHP - it's actually very simple.
Step 1 - turn this JSON object into an associative array so that it's easy to work with:
$input = json_decode(file_get_contents('php://input'), true);
Now we have a variable called $input that is an associative array with all of your mail data - let's set up the variables you need.
$email = $input['email']; //Notice string in brackets is JSON key
$name = $input['name'];
$subject = $input['subject'];
$text = $input['text'];
$telephone = $input['telephone'];
Ok, cool - all of your data you gathered from the front end is now ready for use on the back end. So it looks like you're using the built-in mail() function that PHP offers. I would highly recommend using a library for this as they are typically much more reliable and verbose. My favorite is called PHPMailer - here's a link to their github page https://github.com/PHPMailer/PHPMailer.
If you'd like to use that library, the process is simple.
First, include the autoloader file in your script
<?php
require('PHPMailer-master/PHPMailerAutoload.php');
Next, and they have this documented in numerous examples, you create a new instance of PHPMailer and set some basic variables - this is straight from their documentation and I promise you'll have less headache than if you try the PHP mail() approach https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps.
Best of luck and let me know if I was unclear on anything.

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

json_encode with multidimensional array returning string "array" instead of data

I am passing a multidimensional array back to a .php file using json, jquery, and ajax. My goal is essentially to fill a drop down box (id=project) with multiple entries. Here's some code snippets:
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
In send_input.php (backend), I query a db, and send the information to an array. Then I use json_encode.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => "$proj_option");
echo json_encode($output);
My problem is that this is RETURNING THE STRING "Array".
For example, if I do: response.proj[0], I get "A" returned.
What gives? I've seen a few people with questions about this error, but no definite solution. Any help?
This is because you are casting $proj_option to a string by enclosing it in quotes. Just remove the quotes and you will get the array.

Categories

Resources