I am trying send an array from php to js via ajax but don't it run, no matter what I do.
I'm sure it must be simple but I've tried everything.
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
<link type="text/css" rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scriptJS.js"></script>
</head>
<body>
<div>
<div class="tweets-container">
<p>Loading</p>
</div>
</div>
</body>
</html>
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select>';
var count = 0;
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {
contPrincipalLastTwitter += '<option value =' + response + '>' + response + '</option>';
count++;
},
error: function(e) {
console.log(e.responseType);
);
}
});
console.log(count); contPrincipalLastTwitter += '</select></div></div>'; $(document.body).append(contPrincipalLastTwitter);
});
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
echo json_encode($test);
?>
I reduced it as much as I could, originally this one was sent to a class and this one, having several requests acted according to who have called it.
the problem is that you try to concatenate the same string in two different time and place (first inside the document ready, secondly in the success of the ajax call)
js code:
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select id="test-select"></select></div></div>';
$(document.body).append(contPrincipalLastTwitter);
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {console.log(response);
console.log(response);
for(var idx in response){
$('#test-select').append('<option value =' + idx + '>' + response[idx] + '</option>');
}
},
error: function(e) {
console.log(e.responseType);
}});
});
scriptPHP.php
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
// add header
header('Content-Type: application/json');
echo json_encode($test);
A slightly simpler option
const target = document.querySelector('#target');
$.ajax({
url: 'script.php',
dataType: 'JSON',
success: response => {
for (let key in response) {
const option = `<option value="${key}">${response[key]}</option>`;
target.innerHTML += option;
}
},
error: error => {
// todo
}
});
Related
I want to parse json data created by PHP json_encode in my front end app, i can't do this:
var data= '<?php echo $jsonarr; ?>';
As it is a Cordova app.
Here is my php code:
<?php
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
echo json_encode($arr_login);
?>
My ajax code:
$.ajax({
type:"POST",
url: url,
data:data,
success: function(data){
var res = $.trim(data);
if (res == "Password is inccorrect" || res== "Email is inccorrect") {
$("#errmsg").html(data);
}
else{
var response= JSON.parse(data);
alert(response);
//window.open("dashboard.html?sess=logined&","_self");
}
}
});
Now if I alert data it gives me the valid JSON format as sent by PHP, but I need to convert it to javascript object so I can use it in DOM but JSON.parse gives this error in the console:
VM236:14 Uncaught SyntaxError: Unexpected token / in JSON at position 147
var response = JSON.parse(JSON.stringify(data));
Why do you alert all the json variable which is definetely an object?
I have simulated your process, as #Anik Anwar 's mention JSON.stringify is the solution
<?php
$rowlname = "row";
$rowemail = "email";
$rowfname = "rowfname";
$rowmobile = "rowmobile";
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
$jsonarr = json_encode($arr_login);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var data = '<?php echo $jsonarr ?>';
</script>
<script>
$.ajax({
type: "POST",
url: '/',
data: data,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var res = $.trim(data);
var response = JSON.parse(JSON.stringify(data));
window.alert(response.lname);
}
});
</script>
</body>
</html>
Im returning "true"/"false" (text) from PHP into javascript via AJAX, but my JAVASCRIPT IF condition doesn't seem to be executing even though the condition is correct.
Javascript
var request = $.ajax({
type: "POST",
dataType: "text",
url: "",
data: {
'clientSecret': clientSecret,
'oauthCode':oauthCode
},
});
request.done(function(msg) {
alert(msg);
if(msg=="false"){ <----- DOES NOT EXECUTE
//do stuff
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
PHP
if(checkData($key,$oauthCode)==true){
header("Content-Type: text/plain");
echo "true";
}
else{
header("Content-Type: text/plain");
echo "false";
}
Javascript succesfully alerts "false",
but the if condtion never gets executed.
Is something wrong with the return data type or? What exaclty am i missing here?
Just a suggestion, because I already started to work on this alternative for your question as you found out the problem.
I don't recommend you to work with headers for such tasks. They are sensible to beforehand-outputs, as you saw. You can use the json approach (dataType: 'json') - as #charlietfl kindly suggested, or work with dataType = 'html'.
With json would look something like this:
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Test</title>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
function startTestScript() {
var clientSecret = $('#clientSecret').val();
var oauthCode = $('#oauthCode').val();
var ajax = $.ajax({
method: 'post',
dataType: 'json',
url: 'checkOauth.php',
data: {
'clientSecret': clientSecret,
'oauthCode': oauthCode
}
});
ajax.done(function (response, textStatus, jqXHR) {
if (response === true) {
alert('Response is ' + response + '. COOL!');
} else {
alert('Response is ' + response + '. UPS!');
}
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
alert('Request failed: ' + textStatus + '\n' + errorThrown);
});
ajax.always(function (response, textStatus, jqXHR) {
// alert('Finished executing this cool script.');
});
}
</script>
<style type="text/css">
body {
padding-top: 30px;
text-align: center;
}
button {
padding: 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div>
<label for="clientSecret">Client secret (int)</label>
<input type="text" id="clientSecret" name="clientSecret" value="123">
<br/><br/>
<label for="oauthCode">OAuth code (int)</label>
<input type="text" id="oauthCode" name="oauthCode" value="123">
<br/><br/>
<button type="button" name="testButton" onclick="startTestScript();">
Start ajax
</button>
</div>
</body>
</html>
checkOauth.php
<?php
/**
* Check data.
*
* #param mixed $value1
* #param mixed $value2
* #return TRUE if values are equal, FALSE otherwise.
*/
function checkData($value1, $value2) {
return intval($value1) === intval($value2);
}
// Fetch posted values.
$clientSecret = isset($_POST['clientSecret']) ? $_POST['clientSecret'] : 0;
$oauthCode = isset($_POST['oauthCode']) ? $_POST['oauthCode'] : 0;
// Check data.
$dataIsValid = checkData($clientSecret, $oauthCode);
// Output the JSON-encoded result of checking data.
echo json_encode($dataIsValid);
I'm trying to put a dropdown list for received json data but i m getting below error.please help me on this.i' m not able to figure out what causing the below erroe.it has to print all the values in drop down list.
and the values looks like below.
[{"sno":1,"listOfOperators":"Jio"}
{"sno":2,"listOfOperators":"Airtel"},
{"sno":3,"listOfOperators":"Docomo"},
{"sno":4,"listOfOperators":"Ides"},
{"sno":5,"listOfOperators":"Vodacom"},
{"sno":6,"listOfOperators":"Vodafone"}]
SyntaxError: unterminated string literal
Please find below code for causing above error
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<title>Operators</title>
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json'',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
var str = JSON.stringify(response);
var operatorList;
alert("yes");
alert(str);
alert(response);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value = ' "
+response[i].sno+
" ' >"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
});
</script>
</head>
<body>
<div class="logo"></div>
<div class="op-block">
<h1 style="text-align: center;">Please Select an Operator</h1>
<select id="opList">
<option value =' '></option>
</select>
</div>
</body>
</html>
please help me on this
After making sure your response is valid, you should loop through it so:
var response = [
{"sno":1,"listOfOperators":"Jio"},
{"sno":2,"listOfOperators":"Airtel"},
{"sno":3,"listOfOperators":"Docomo"},
{"sno":4,"listOfOperators":"Ides"},
{"sno":5,"listOfOperators":"Vodacom"},
{"sno":6,"listOfOperators":"Vodafone"}
];
for (var i = 0; i < response.length; i++ )
{
console.log(response[i]);
}
I work with the api new york times search engine, my question is simple, i just want to change parameters in my url using a input type text in my html.
How can i do that ?
End date and sort are one of the parameter, i just want to know how can i change the string with an input field in html.
here a copy of my code :
html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel='stylesheet' type="text/css" href="nyt.css">
<link rel='stylesheet' type="text/css" href="font.css">
<link rel='stylesheet' type="text/css" href="grille.css">
</head>
<body>
<div class='container'>
<button type="submit" id='searchButton'></button>
<input type="text" id='searchTerm' placeholder="search">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src='nyt.js'></script>
</body>
</html>
js :
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
var searchTerm = document.getElementById('searchButton');
url += '?' + $.param({
'api-key': "[API KEY]",
'end_date': "19440606",
'sort': "newest"
});
$.ajax({
url: url,
method: 'GET',
q: searchTerm,
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
You can get the value of your input field with the “value” property, like so:
var searchTerm = document.getElementById('searchButton').value;
See also: JavaScript: how to get value of text input field?
function sendRequest(searchTerm) {
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "[API KEY]",
'end_date': "19440606",
'sort': "newest"
});
console.log(searchTerm);
return $.ajax({
url: url,
method: 'GET',
q: searchTerm,
});
}
document.querySelector('#searchButton').addEventListener('click', function(e){
e.preventDefault();
var query = document.querySelector('#searchTerm').value.trim();
if (query.length > 0) {
sendRequest(query)
.done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
}
})
I want to get the data of the select tag id="departmentselect" so that the values of it will be stored in the mysql database before submitting the form. I heard that you will use AJAX to get the data before you submit the form. Because when I select the College select tag and its corresponding values of the department select tag it will only store a number in the department of the database.
Example MYSQL database:
In the query of mysql, the department did not get the values of the JSON file. It only display the number.
Here is my PHPCode
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
Script Type
Here is the script for using ajax but it did not seem to have any effect.
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
JQUERY Code file name GetCollegeJsonData.js
I get the JSON data from the file and read it into my Jquery file and then link the file using script to my php code
//Get json
$('body').on('change', '#collegeselect', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + key + "'>" + val + "</option>");
});
});
})
Its JSON File
{
"College of CAS": ["Biology", "English", "LIACOM", "Library & Information Science", "Mass Communication", "Philosophy", "Political Science", "Psychology"]
}
Is my Ajax function is incorrect?
Your ajax method code has syntax error and, when you use post method you have to post data using data option not with URL. data should be in json object or query string.
Your ajax function should be
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$.ajax({
type: 'POST',
url: 'Signup.php',
data: {select: $('#departmentselect').val()},
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
I have edited your code as below.
Kindly give it a try.
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e)
{
if($('#departmentselect').val() != '')
{
$.ajax
({
type: 'POST',
data:{select:$('#departmentselect').val()},
url: 'Signup.php',
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
For GetCollegeJsonData.js, ihave modified as follows:
//Get json
$('#collegeselect').on('change', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + val + "'>" + val + "</option>");
});
});
})