jquery POST response successful BUT data empty - javascript

im using jquery to send a post to a session endpoint of my api to get a login token. the request returns success, however the data is empty. if i do the same request in cURL it returns json.
Im new to jquery. does anyone have any suggestions as to what the problem might be?
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE> login </TITLE>
</HEAD>
<LINK rel="stylesheet" type="text/css" href="login.css" />
<BODY>
<DIV id="container">
<DIV id="header">
<IMG src="image.bmp" alt="logo" style="width:64px;height:64px;"/>
<H1> my service </H1>
</DIV>
<DIV id="content">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function()
{
$.post("www.mydomain.com/api/session",
{
username: "batman",
password: "123"
},
function(data,status)
{
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
<DIV id="loginform">
<form method="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<button> welcome! </button>
</form>
</DIV>
<DIV id="description">
<P>mydomain description</P>
<P>Join now to see what people are doing near you!</P>
</DIV>
<DIV id="register">
<P>Dont have an account with us? </P>
<P>Register here now !!</P>
</DIV>
</DIV>
<DIV id="nav">
</DIV>
</DIV>
</DIV>
</BODY>
</HTML>

WOW! i found the problem, it was so simple. i just needed to use http:// in front of my url.
Thanks for every ones time and help!.

Moreover Punit's answer, I advice to use $.on() method which is better than .click() function.
$(function() {
// equals to $(document).ready(function(){ but faster to wright
$("#loginform").on('click', 'button', function() {
//Punit's Code (that is good !!)
$.ajax({ url: 'your_url_here',
data: {username: 'batman' , password : "123"},
type: 'post',
dataType: "json",
success: function(output) {
alert(output);
}
});
});
});

The issue's likely to be that you need to stop the form from being submitted after your button click event is executed. As written, once the script has completed, the page is refreshed and there is no opportunity to process the results of the post request. Return 'false' from the click function:
$("button").click(function() {
$.post("www.mydomain.com/api/session",
{
username: "batman",
password: "123"
},
function(data,status)
{
alert("Data: " + data + "\nStatus: " + status);
});
return false;
}
);
This done you should see whether your post request is returning any data. Note that because you're posting to a directory, the script will default to looking for an index file, e.g. index.php. If that's an issue, change your URL to point directly to the relevant server-side script.

Below is the for creating an Ajax call, now what you have to do it. You have to return the data into json format from the URL, then try console.log(output) in the success function, you will get the idea that hot it is works.
$.ajax({ url: 'your_url_here',
data: {username: 'batman' , password : "123"},
type: 'post',
dataType: "json",
success: function(output) {
alert(output);
}
});
let me know if you dont understand anywhere,

Related

Laravel Ajax JSON Object is empty

I'm working on a laravel web app, I'm relatively new to laravel so I'm not very familiar with the ajax tokens and such, but I believe I have set it up correctly.
Below is my Ajax code for a test page that I want to try and send data from.
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'testSend',
data: {
test: 'hello'
},
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
Here is my form:
<div class="flex-center position-ref full-height">
<div class="content">
<form action="testSend" method="post" enctype="multipart/form-data">
<button type="submit" id="btn"> submit</button>
</form>
</div>
And here is a simple route that I have setup just to test this:
Route::post('testSend', function (Request $request) {
return response()->json($request);
});
However when I go to check the network in chrome, the JSON Object is empty.
The empty JSON Object:
I'm pretty new to this, I have learned it but never really tried to create a web app until now. I have searched everywhere, but no one seemed to have the same problem, maybe they did but I just don't know.
The problem might just be a dumb mistake, but I really can't figure it out ):
Thanks.
Rather than passing Request instance try this:
return response()->json($request->all());

JavaScript/JQuery/HTML - Use output of one script as variable in another script

I am making a small chrome extension. Its purpose is to make an API call to retrieve some JSON which is then stripped out to show only Name, Email & Team which is then presented to the user. The user then has the option to send that information to a slack channel via a button.
Everything works fine, my API call shows the correct information, My Webhook for slack works fine with a test message.
My issue is I dont know how to put whats returnd from my API call as variables to send to slack
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
I.e.
var text = '$('.Name') + 'was contacted from' + $('.Teams') + 'Their email addres is' + $('.Email')''
Example slack message
John Smith was contacted from Sales Team Their email address is jsmith#mysite.com
HTML
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<meta content="noindex, nofollow" name="robots">
<meta content="noindex, nofollow" name="googlebot">
<script src="jquery-git.js" type="text/javascript"></script>
<script src='apicall.js'></script>
<script src='slackapi.js'></script>
<title>Call Logger</title>
</head>
<style>
</style>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h3>Call Logger</h3><br>
<h2><div class="Name"></h2>
<h2><div class="Address"></h2>
<h2><div class="Teams"></h2>
<h2><div class="Email"></div></h2>
<h2><div class="Role"></div></h2>
<br>
<br>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</fieldset>
</form>
</div>
</body>
</html>
apicall.js
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
slackapi.js
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
I obviously can't reproduce your setup, but, depending on what kind of pages are apicall.js and slackapi.js - there are some restrictions and particularities in the case of content/background pages -, I think you can send the text variable (or even its constituent parts, e.g. name, teams, email, using an array) to slackapi.js by message passing.
You send the message from apicall.js usually using chrome.runtime.sendMessage() (other options are available, depending on context), and you receive the message using a listener, e.g. chrome.runtime.onMessage.addListener(). For the message to be received, slackapi.js or any other JS file needs to run, so if it doesn't it needs to be injected using chrome.tabs.executeScript(), for example.
I'm not sure if this will help you, but at least I tried.

Login Process with jQuery Ajax and PHP

Hey guys I need some help.
My problem is the error div is not displaying the content that I want it to appear in the success function of my AJAX request. I tried alerting the response and it returns true if user-name and password is correct and returns false if incorrect.
I don't know why its not working.
so this is my code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container" name="main-div">
<div id="error">
AA
</div>
<center>
<div name="login-div">
<h2>LOGIN PAGE</h2>
<form method="post" class="login_form">
Username: <input type="text" name="username"></br></br>
Password: <input type="password" name="password"></br></br>
<button type="submit" name="button_login" id="button_login">LOGIN</button>
</form>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
$("#button_login").click(function(){
var data = $(".login_form").serialize();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: data,
beforeSend: function(){
alert(data);
},
success : function(response){
//alert(response);
if(response=="true"){
$("#error").html("CORRECT USERNAME AND PASSWORD")
//window.location="home.php";
}else{
$("#error").html('<a>WRONG</a>');
});
}
}
});
});
});
</script>
</body>
</html>
Thanks in advance
There is an extra closing bracket in the script what you wrote. Try to open the page in the chrome and open the developers console to see the syntax error.
Login.html:44 Uncaught SyntaxError: Unexpected token )
I corrected the syntax as below
$(document).ready(function(){
$("#button_login").click(function(e){
e.preventDefault();
var data = $(".login_form").serialize();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: data,
beforeSend: function(){
alert(data);
},
success : function(response){
//alert(response);
if(response=="true"){
$("#error").html("CORRECT USERNAME AND PASSWORD")
//window.location="home.php";
}else{
$("#error").html('<a>WRONG</a>');
}
},
error : function(response) {
$("#error").html('error'+ error);
}
});
});
});

Send a POST request in jQuery when a div is clicked

I am having trouble figuring out how to get the following done.
click on a paragraph element
send a .post request using jQuery
get the sent data from the server to display in the paragraph
I've searched quite a bit and tried using some of the solutions proposed but it failed.
Here's my folder structure:
+ html
- index.html
+ js
- eventhandling.js
+ php
- test.php
HTML
<div class="channel" id="channel1">
<p class="title">CHANNEL 01</p>
<p class="stb_sub_menu" id="model">STB Model</p>
<p class="network_sub_menu" id="network">Network</p>
<p class="smartcard_sub_menu" id="smartcard">Smartcard</p>
<p id="reboots">Reboots</p>
</div>
<p id="demodata">Demo Data</p>
PHP
<?php echo "PHP script -> You called master?"; ?>
JS
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").val("data");
});
});
The click event is successful because the alert pops up. Nothing shows on the Firebug console window.
Might be the service URL you passed into post is wrong (according to the folder structure).
The code must be like this.
$(".channel").click(function(){
var postData = {"name":"john"};
$.ajax({
type: "POST",
url: '../php/test.php',
data: postData ,
contentType: "application/json",
dataType: "json",
processdata: true,
success: function (response) {
},
error: function(error){
}
});
});
This will work for you.
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").text(data);
});
});

AJAX call to rest service to post the data from HTML form

<html>
<body>
<form method="POST">
<label>username</lable>
<input id="username" name="username" type="text">
<label>emailid</lable>
<input id="emailid" name="emailid" type="text">
<button id="enter" type="submit">submit</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
var userName = $("#username").val();
var emailId = $("#emailid").val();
$($enter).click(function () {
$.ajax({
type: 'POST',
url: ".....rest service url....",
dataType: JSON,
data: {
"UserName": userName,
"EmailId": emailId
},
success: function (data) {
alert("success");
}
error: function (e) {
alert("error" + e)
}
});
});
});
</script>
</body>
</html>
I'm trying to post the form field in rest service which expects a JSON response.
I'm getting an alert error message (object Object)
I'm not getting where the error is.
You can try $.post instead of $.ajax
$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});
Just make sure that parameters you are passing matches with your REST service.
$($enter).click(function () {
this part of code looks invalid, provide a correct selector to the click function.
First change this
$($enter).click(function to
$("#enter").click(function () {
Are you sure the the service you written for this task is a post service...some times i do the mistake like post data and write service for getting data.If you can show your service structure it will help to have a better insight.

Categories