How can i target javascript variable using jquery? - javascript

I want to know how an I target javascript variable using jquery. Here is situation of my web page where I want to use some details that are stored in javascript variable which I will use in user registration. My page codes looks like this
<html>
<head>
<script>
var userData =
{"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
</script>
</head>
<body>
<form id="register">
<button id="regbtn">Register</button>
</form>
</body>
<script src="jquery.js"></script>
<script src="custom.js"></script>
</html>
So now how can I use custom jquery function that will target "userData" variable on click of "regbtn"?
I am doing in my custom javascript is
$( document ).ready(function() {
$('#regbtn').click(function(){
//do something here that will target that userData variable and will send its data using ajax
//$ajax function will send data to page with details that user entered and userData
});
});
But I don't know how to target that userData variable using json. This variable in json data format out put of php. Can anyone help me?
And with negative votes I'd appreciate if you tell me why are you voting negative this question. I am not pro so asked this question. May be this is stupid but not for me. So thank you anyways for seeing this question

If you need to access your json object "userData", you'll want to add the following in your click function:
var country = userData['country'];
var region = userData['region'];
and so on.
You could send the whole object without separation if you plan on sending it via AJAX. Below is an example of this:
$(function() {
var userData = {"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
$('#regbtn').click(function() {
$.ajax({
url: "someURL",
data: userData,
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, textStatus, jqXHR) {
// check if response was valid/invalid or do other stuff here
});
});
});

Related

i am new to ajax and jquery so i dont know what is wrong in my code

I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
this is demo.txt
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
this is my console error
enter image description here
This is how your URL can use ajax, because Ajax has cross domain restrictions
If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page
Pls follow the documentation provided at
jQuery.ajax() | jQuery API Documentation
It should work fine when you include in the same order.
Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.
Example of a simple ajax function with passing user data (namely data1 and data2):
$.ajax({
type: "post",
data: {
user_data1 : data1,
user_data2 : data2,
},
url: YOUR_FUNCTION_PATH,
success: function(data){
// After success passing data to YOUR_FUNCTION
// Handle what you do next
},
error: function (request, status, error) {
// Error of passing data to YOUR_FUNCTION
// Debug to see what is wrong
}
});
Then in your YOUR_FUNCTION and if you sending data to PHP function,
$user_data1 = $_POST['user_data1'];
$user_data2 = $_POST['user_data2'];
If you are using the old one, CodeIgniter, it is pretty simple to get the data.
$user_data1 = $this->input->post('user_data1');
$user_data2 = $this->input->post('user_data2');
Your URL may need to start with localhost, for example: http://localhost :8080

jQuery - Finding xml children based on a variable argument

I am creating an application that converts an online form into various PDF forms to reduce admin burden. I am using an XML file so that users can enter a course code and the form will automatically populate some of its data to fill in the course information, however for the code below I am just using test files to figure it out first.
The user is to enter the course code in a text input and click a button to call Ajax to read the xml and create variables to populate the form. I have looked through dozens of tutorials and forums and can't seem to solve my problem - I need to filter the child nodes according to the course code entered, but I can only get it to work by entering the course code as text in the js file, when I attempt to use a variable argument it doesn't work and I have tried so many different ways.
HTML...
<html>
<head><title>XML Reader</title></head>
<body>
<input type="text" id="argumentText">
<input type="button" id="button" value="process">
<input type="text" id="outputText">
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
XML...
Will have more coursecodes and child nodes eventually when I can get jQuery to work
<?xml version="1.0"?>
<course type="array">
<coursecode>CWI416D01F
<description>Signmaking L2</description>
</coursecode>
<coursecode>CWI490D01F
<description>Business Admin L2</description>
</coursecode>
<coursecode>CWA061D01S
<description>Dental Nurse L3</description>
</coursecode>
</course>
My jQuery...
Note that the code below does actually work, but the outputVar that is created doesn't use the argumentVar at all...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//Doing it this way works
var outputVar = $(data).find('coursecode:contains(CWI416D01F)').children('description').text();
//The outputVar is output as text in the outputText field, in this case "Signmaking L2"
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
But I want the outputVar to take the argumentVar as the text argument in contains() rather than having to set updozens of cases in a switch, I have tried several methods, here are a couple of examples below...
var outputVar =
//Attempt 1
$(data).find('coursecode:contains(argumentVar)').children('description').text();
//Attempt 2
$(data).find('coursecode:contains('"+argumentVar+"')').children('description').text();
//Attempt 3 & 4 (I added an ID into each xml coursecode tag for this attempt)
$(data).find('coursecode[id="argumentVar"]').children('description').text();
$(data).find('coursecode[id=argumentVar]').children('description').text();
I've even tried a bunch of other different ways such as attempting to parse, if statements, filter return functions, you name it. Hopefully there is someone out there who can answer this, ideally with a really simple snippet of code.
This question was answered thanks to Ryan Wilson, here is answer in case anybody else confronting this problem...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//This code finds a single xml node using the argumentVar variable
var outputVar = $(data).find('coursecode:contains(' + argumentVar + ')').children('description').text();
//The outputVar is output as text in the outputText field as according to whatever argument the user entered into argumentText
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed

How to get js variable's value into a PHP variable later used for MySQL without submit or click on any button using JS/Jquery? [duplicate]

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

jQuery and Php variable calling

I have a problem with jQuery and PHP.
I have a .php file that contains a variable, for example var surname = "";
The problem that I am facing is, I want remotely access it from a .html file and give it a value from another variable in the .html file.
Is there any way to do it?
Thanks.
Ok, so you said you wanted to get a variable from HTML and send it to the PHP file to change data, that is what the variable 'varfromhtml' is.
You just need to give it a value you want to send, you can get the value of a div using jQuery eg
<div id="div">data</div>
var varfromhtml = $.("#div").val();
The variable 'varfromhtml' is now equal to 'h08sahdas', you can mess around with that to get it right for you.
Here is the final script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var varfromhtml = $.("#div").val();
$(document).ready(function(){
$.ajax({
method: "POST",
action: "myfile.php",
data: {
varfromhtml:varfromhtml
},
success: function(data){
$('#mydiv').val(data);
}
});
</script>

How to display a json data from a existing url using ajax call

I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about

Categories

Resources