How to form a standard POST request with a parameter with JavaScript and jQuery Knob?
Here is what I got:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="jquery.knob.min.js"></script>
</head>
<body>
<input type="text" data-angleoffset=-125 data-anglearc=250 data-fgcolor="#66EE66" value="50" class="dial">
<script>
$(".dial").knob({
'release' : function (sendpostresp) {
$.ajax({
url: "publish.php", //the page containing php script
type: "POST", //request type
success: function (result) {
alert(result);
}
});
}
});
</script>
</body>
</html>
I need to save the value of the knob on release. The PHP part waits for the POST and saves the value to a database, and it works.
In my opinion, my code should send the current value of knob to the PHP script with POST. But I see no parameters in console, just an empty POST response.
Unfortunately, the official jQuery Knob docs don’t provide sufficient instructions. Please, help me with code examples, how to send the current value from the jQuery knob through POST?
You just need to add a data property to your ajax request. It could look like this:
$(".dial").knob({
'release' : function (sendpostresp) {
$.ajax({
url: "publish.php", //the page containing php script
type: "POST", //request type
data: {
foo: sendpostresp
},
success: function (result) {
alert(result);
}
});
}
});
According to Knob docs, the parameter in the 'release' callback function is the current value of the dial. Simply stick that into your data object on the ajax request and it will be sent to your server-side code that handles the request
Related
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
I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}
I need to simulate submitting a form on an external site, I already had it working for other sites but now the external site expects json formatted values as parameters which is being hard to accomplish.
Before the server expects json I had it perfectly working with this (note the javascript simulates submitting the form, and the form is coded to relate to the external site):
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function load()
{
window.document.login_form.submit();
return;
}
</script>
</head>
<body onload="load()">
<form name="login_form" method="post" action="http://external.webserver.com/web/session/authenticate">
<input type="hidden" name="name" value="andres" />
<input type="hidden" name="phone" value="593123123" />
</form>
Here I attacha an image that profs that it will work if I would post the body as json data.
As a solution I've tried other ideas like suggested here POST data in JSON format
function load()
{
var frm = $(document.login_form);
dat = JSON.stringify(frm.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
//window.document.login_form.submit();
return;
}
But that approach takes me several other problems regarding related to 'Access-Control-Allow-Origin' which I won't fix as I don't own the server to which I want to post.
So would any one provide a better approach to make a json post (or post the body) to an external server?
You can't submit application/json using a form
You can't read the response from a different origin using JavaScript (unless that origin grants permission)
The only option left is to have your form or JavaScript send the data somewhere else (that you do control) and have the server responsible for handling that somewhere else issue an HTTP request of its own to the server you want to contact and then relay the response back to the browser.
This answer was posted in 2014; a lot has changed since then, and this answer is more/less irrelevant now.
If the server is expecting a JSON payload, and if it works from hurl.it, you probably aren't having CORS issues.
$.post by itself can't set the content-type header; you need to use the parent $.ajax and make sure you're posting a proper JSON payload (try logging dat to console and checking it against jsonlint).
Your example also has several syntactical mistakes, such as the lack of quotes around document.login_form and the incorrectly formatted $.post.
Try cleaning it up:
var frm = $('document.login_form');
data = JSON.stringify(frm.serializeArray());
$.ajax(frm.attr("action"), {
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}, function (data) {
console.log(data);
});
I've been trying out lots of tutorials and SO question to find a way to make the below code work in obj-c. Its a json response from the server, but nothing i've tried works. How should I make the below code in obj-c?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajax({
url: "http://myjsonurl.com",
data: { employerID: "1", startDate: "2013-09-13", endDate: "2013-09-15" },
success: function(data) { console.log(data); }
});
</script>
</head>
</html>
Change this response page to be purely JSON like so,
{ "employerID": 1, "startDate": "2013-09-13", "endDate": "2013-09-15" }
Make sure to put quotes around those keys unless they are variables.
You can use a third-party tool (linked to one below) to call this url and get the response as data, then convert the data to a NSJSONSerialization object in the completion block.
https://github.com/andrewapperley/AFFNetworking
This is not only json response HTML script also came ,
Inform to your web-service person clear the HTML script give as array , dictionary format result
I would like to parse JSON array data with jquery ajax with the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "jsonp",
success: function (xml) {
alert(xml.data[0].city);
result = xml.code;
document.myform.result1.value = result;
},
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
My JSON data is:
{"Data": [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}
But i am not getting any output...anybody please help out...
Concept explained
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
You need to use the ajax-cross-origin plugin:
http://www.ajax-cross-origin.com/
Just add the option crossOrigin: true
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
Your JSON-data contains the property Data, but you're accessing data. It's case sensitive
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "json",
success: function (xml) {
alert(xml.Data[0].City);
result = xml.Code;
document.myform.result1.value = result;
},
});
}
EDIT Also City and Code is in the wrong case. (Thanks #Christopher Kenney)
EDIT2 It should also be json, and not jsonp (at least in this case)
UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim
Try
alert(xml.Data[0].City)
Case sensitivly!
you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);
alert(xml.data[0].city);
use xml.data["Data"][0].city instead
use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5