I'm using xampp-control to emulate a local server. I have a html file and i'm trying with ajax to post some data into a json file. I can get the data from the json, but when I'm trying to post doesn't work.
here is the html
<!doctype html>
<html class="no-js" lang="">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<h1> Family Perez</h1>
<form>
<label>Name</label><input type="input" id="name" name="name"></input>
<label>Last Name</label><input type="input" id="lastName" name="lastName"></input>
<input type="submit" id="submitBtn" value="Add family Member" name="submit"></input>
</form>
<div></div>
</body>
</html>
and here is the js
$(function(){
$('#submitBtn').click(function(e){
e.preventDefault();
var firtsName = $('#name').val();
var lastName = $('#lastName').val();
$.ajax({
type: 'post',
url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
dataType: 'json',
async: false,
data: {name: firtsName, last: lastName},
success: function(newMember){
alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
}
})
});
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://localhost/angel/Jquery_advanced/ajax/family.json',
success: function(data) {
$.each(data, function(i, member){
$('div').append('<p>'+ member.name + ' ' + member.last +'</p>');
})
}
});
});
the file containing JSON data (http://localhost/angel/Jquery_advanced/ajax/family.json) looks like:
[{"name":"Juliseth","last":"Hernandez"},{"name":"Angel","last":"Perez"}]
The alert show undefined undefined has been added
Open debugging tool like Inspect Element or Firebug (Shortcut F12) in your preferred browser => Network => check ajax response,
If response is null or status code is 204 that means no data returned from the server, so that response data object would be undefined.
Another way,
$.ajax({
type: 'post',
url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
dataType: 'json',
async: false,
data: {name: firtsName, last: lastName},
success: function(newMember){
alert("Response data : "+newMember);//check your response here
alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
//If newMember is array then your have to access it via index as Anik Islam Abhi suggested
}
})
Note : If you are directly requesting on json file then your idea behind post request to json file is wrong. For that you need to use server side language like Java, PHP, etc.
I believe that is because well... the POST data is undefined. Both of these are not actually getting any data:
var firtsName = $('#name').val();
var lastName = $('#lastName').val();
There is nothing in the .val()'s.
Your two input's have no values, and therefore nothing is being posted. Your get is adding content to the div, and it looks like you may be wanting to actually add the content to the inputs values?
Related
I'm sending form data via jquery and cannot get the window.location.assign() to fire off. I am getting a successful submission. I've also tried window.location.href =
<form>
<div>
<a id="submitDesk" type="button" class="btn submitDesk">Submit Request</a>
</div>
</form>
$( document ).ready(function() {
$( "#submitDesk" ).click(function() {
var firstname = document.querySelector('#firstname').value;
var lastname = document.querySelector('#lastname').value;
var email = document.querySelector('#email').value;
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email=' + email + '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('/thank-you/');
}
});
});
});
Kindly use below. data parameter string was not proper, String was getting break, SO i have added " ' " to make it a proper string.
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email='+ email+ '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('http://foo.com/thank-you/');
}
});
The backend file was sending incorrect responses causing there to always be an error even though the form was a success.
If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]
You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File
I have below code for submitting the form with ajax but only first instances out of 5 comment box are being submitted for balance I am getting discription=" and also being inserted to the wrong id. here is my code and live example. I want to allow users to comment on any items
http://way2enjoy.com/app/jokestest-991-1.php
$output .='<div id="'.$idd.'" align="left" class="messagelove_box" ><div class="content_box_1">
<div class="content_box_2z"><sup class="joke_icon"></sup></div>
<div class="content_box_3_title"></div>
<div class="content_box_3_text">'.nl2br($cont).'</div>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr(\'action\');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden'. $idd.'").value;
$.ajax({
url: url,
data:{
\'action\':\'addComment\',
\'comment\':comment,
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
\'action\':\'getLastComment\',
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
$(\'#jokes_comment\').val("");
console.log(result[0].description);
$("#header ul").append(\'<li>\'+result[0].description+\'</li>\');
},
error: function(){
alert(\'failure\');
}
});
},
error: function(){
alert(\'failure\');
}
});
return false;
}
</script>
<div id="header" class="content_box_31_text"><ul id="commentlist" class="justList">'.$contpp.'</ul></div>
<form method="post" action="check/process2.php" class="button-1" onSubmit="return ajaxSubmit(this);"><input type="hidden" value="'. $idd.'" id="joke_id_hidden'. $idd.'"><input type="text" id="jokes_comment" value="" name="jokes_comment">
<input type="submit" value="comment"></form>
</div></div>
';
The code posted doesn't tell the full story, but looking at the URL mentioned does. The snippet you've posted is being repeated over and over again, identically in the page. That means that each definition of the ajaxSubmit function overwrites the previous one, and that you have multiple input elements all with the same id. No wonder the page is confused as to what to do. You only need one submit function, if it's written properly it can handle all the different comment inputs. And your comment inputs can't have the same id each time, but they can have the same CSS class, and since they are all within the form, when we submit a specific form, we know the context we are working in, and jQuery can automatically find all the fields in the form for us, without us having to write code to access them all individually.
So..with that design in mind, define your javascript like this, and make sure it only gets rendered once in your entire page output. I've re-written it slightly to take advantage of the easier syntax provided by jQuery.
$(".comment-form").submit(function(event) {
event.preventDefault(); //prevent the default postback behaviour
var form = $(this);
var jokeID = form.find(".joke_id").val();
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data: $(this).serialize(), //automatically finds all the form fields and puts the data in postback-friendly format
success: function(result) {
//I'm not convinced you need this second ajax call - can't you just write the contents of the input box directly into the list? But I'll leave it here in case you want it
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data:{
"action":"getLastComment",
"joke_id": jokeID
},
success: function(result) {
form.find(".jokes_comment").val("");
$("#header-" + jokeID + " ul").append("<li>" + result[0].description + "</li>");
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
});
Secondly, make the PHP that generates the comment markup for each joke look like this:
<div id="header-'.$idd.'" class="content_box_31_text">
<ul id="commentlist" class="justList">'.$contpp.'</ul>
</div>
<form method="post" action="check/process2.php" class="button-1 comment-form">
<input type="hidden" value="'. $idd.'" name="joke_id"/>
<input type="hidden" value="addComment" name="action" />
<input type="text" class="jokes_comment" value="" name="comment" />
<input type="submit" value="comment">
</form>
I wanna get inputs using a form on my page and submit those values to a php hosted on another external site. Request maker extension shows the Header Authorization being passed along with other inputs when submitting data on the external site.
The result is probably an xml file (Student Record).Need to pull and show it as result.
Tried a lot using $.Ajax and jquery in vain. Please help.
[1]: http://i.stack.imgur.com/rDO6Z. jpg
[2]: http://i.stack.imgur.com/92uTh. jpg
function myFunction() {
var name = document.getElementById("name").value;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://externalsite.cpm/results.php.php",
data: dataString,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', "Basic XXXXXXXXXXXXXXXXXXXXXXXXX" ); or xhr.setRequestHeader('Authorization', "Basic " +btoa(ser_user + ':' + ser_pass));
},
cache: false,
success: ???
xmlhttp.open("POST","your_url.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=" + name + "&email=" + email);
<body>
<form action="http://externalsite.cpm/results.php" method="post" >
Enter Your Name<br>
<input type="text" name="name" >
<br>
<input type="submit" onclick="myFunction()" value="Submit">
</body>
How do I add this header authorization when submitting values from my page to external php? Please Help !
Its bit late but still posting the answer for future readers who might face the same issue.
Please do not provide the form submit url (action) and method type (POST) inside the html code when it is explicitly mentioned inside the ajax request.
Notice the corresponding changes added in the code snippets given.
Html form code :
<form><!---Removed form submit url-->
<input type="text" id="keyName" value="testValue">
<!---Id attribute added to input field to be submitted--->
<input type="button" onclick="myFunction()" value="Submit">
<!---Input type is button NOT submit--->
</form>
Javascript code:
function myFunction(){
var dataValue = $("#keyName").val();
$.ajax({
type : 'POST',
//remove the .php from results.php.php
url : "http://externalsite.cpm/results.php",
//Add the request header
headers : {
Authorization : 'Bearer ' + 'XXXXXXXXXXXXXXXXXXXXXXXXX'
},
contentType : 'application/x-www-form-urlencoded',
//Add form data
data : {keyName : dataValue},
success : function(response) {
console.log(response);
},
error : function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err);
}
}); //End of Ajax
} // End of myFucntion
Update :
PHP service results.php
<?php
print_r($_POST["keyName"]);
?>
I had a similar issue, needed to add authentication header name and authentication token value in the HTTP POST request headers. Added this javascript interceptor function in one of the JSPs that forms the HTML panel that's part of every page in the web application.
// this will add employee authentication headers to every ajax call
(function() {
var site = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.setRequestHeader("${employee.role.header}", "${employee.auth.secret}")
return site.apply(this, [].slice.call(arguments));
};
})();
I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!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>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());