I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from
Related
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I'm playing around with a twitter API wrapper for Node right now and am trying to figure out how to pass a query parameter from an HTML form to an AJAX get request and have that parameter then passed into my Express route, rather than just having the form action go directly to the route.
Here's my HTML code
<form id="searchTerm">
Keyword:<input id="keyword" type="text" name="q" placeholder="Keyword">
<input type="submit">
</form>
My client-side Javascript
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And then my Node.JS route:
// Search by keywords or phrases
app.get('/search/tweets/term', function(req, res) {
var q = req.query.q;
// Accesses the Twitter API and pulls back the respective tweets
client.get('search/tweets', {q: q, count: 100, lang: 'en', exclude: 'retweets'}, function(error, tweets, response) {
if(!error) {
res.send(tweets);
} else {
console.log(error);
res.status(500).send(error.stack);
}
});
});
I'm getting a "Query Missing Parameters" error message in my terminal whenever I input a value into the form, however. Not sure what I'm doing wrong.
UPDATE
Got it working via the following:
$(document).ready(function() {
$('#searchTerm').on('submit', function(e) {
e.preventDefault();
var q = $('#keyword').val();
$.ajax({
type: 'GET',
data: {q: q},
url: '/search/tweets/term',
success: function(data) {
console.log(data);
}
})
})
})
However, since I'm implementing e.preventDefault(), I'm losing the query parameters within my URL. Since I want to give users the ability to share URL's to specific keywords, is there any way to be able to keep these parameters intact in the URL while still getting the JSON sent client side? Or will have to just manipulate the JSON on the server side and have the data be rendered in via a template engine?
Try this
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term?q=',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
below is an ajax but it wont work, what seems be the problem? assume that I have requestparser.php and inside it i have "echo "yes ajax work!";".
$(document).ready(function(){
// start ajax form submission
$.ajax({
url: "requestparser.php",
type:"POST",
data: ({ "pulldata" : "oy" }),
success:function(e){
if(($.trim(e)=="success")){
alert("yes");
}else{
alert("no");
}
},error:function(){
alert("error");
}
});
});
as above ajax function ,the process should be, on load it will send first a post request to requestparser.php with a post name of "pulldata" and post content of "oy" and when the requestparser receive that post request from the ajax so then respond with "yes ajax work!" and since the respond from requestparser.php is not equal to success then it should display "no".
any help would be greatly appreciated
I tried to debug your code and it worked fine for me. So can you try this code and say what error it shows ?
$(document).ready(function () {
$.ajax({
url: "test.php",
type: "POST",
data: ({
"pulldata": "oy"
}),
success: function (e) {
console.log(e);
},
error: function (e) {
console.error(e);
}
});
});
test.php
<?php
var_dump($_POST);
One more thing, just for confirmation, you have included jQuery in your page before using ajax right ?
myscript.js below is outputing:
[{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}]
myscript.js:
if (addList.length) {
$.ajax($.extend({}, ajaxObj, {
data: { "addList": JSON.stringify(addList) },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
}
The JSON data above has to be sent to my script.php below:
if( isset($_POST["addList"]))
{
$addList = json_decode($_POST["addList"], true);
var_dump ($addList);
echo "test";
exit();
}
Although the data is correct and myscript.php is being called it isn't returning anything. I get:
NULLtest
I tried using GET, instead of POST but the result is the same, what is wrong with the code above?
EDIT:
Here's the ajaxObj used in the ajax request:
var ajaxObj = {
dataType: "json",
url:"../myscript.php",
type: "POST",
async: true,
beforeSend: function (jqXHR, settings) {
$grid.pqGrid("showLoading");
}
};
From the PHP Docs on json_decode:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So it is most likely that there is some error in your JSON data that is preventing json_decode from parsing it correctly, I've ran that snippet through jsonlint and it does say that it's valid JSON, but it's worth checking a larger sample of the data you send to the server for inconsistencies.
Other than that, is there any reason that you are calling JSON.stringify on the data object prior to sending to the server? I would try just sending the object itself as the data parameter of your AJAX call like so:
$.ajax($.extend({}, ajaxObj, {
data: { "addList": addList },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
And see if that helps:
EDIT
I should have noticed in my original answer, you will not need to call json_decode on your posted data, jQuery encodes the data as post parameters correctly for you; It should be accessible within your PHP script as an associative array, try replacing your current var_dump statement in your PHP var_dump($_POST['addList'][0]['orcamento']); and you should be good to go.
First of all, be sure you are posting to a php file, use firebug or similar tools to track your script..
I don't see the part you defined the target PHP file on your javascript file..
A regular javascript code can look like this :
jQuery.ajax({
type : "post",
dataType : "json",
url : 'target.php',
data : {foo:bar },
success: function(response) {
// do something with response...
}
});
If you see that you are posting to the right php file the right parameters on firebug, try to use $_REQUEST if $_POST not working..
Firebug will show you the response of PHP file.. so do a print_r($_REQUEST['addList']) to see what is going on...
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.