Rendering the response of a jquery POST request in NodeJs - javascript

Functionality:
The functionality of this code is to update user details on the user Profile-page.
Code:
Profile.ejs
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
//alert(json);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}, false);
});
})();
</script>
<div id="res">
<h4>
<%= status %>
</h4>
</div>
<form id="test" action="/profile" method="post">
<input type="text" name="name" id="name" value=""/>
<input type="text" name="about" id="about" value=""/>
<input type="text" name="hobbies" id="hobbies" value=""/>
<input type="submit" value="send" class="btn btn-primary btn-block"/>
</form>
Index.js
router.get('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:''});
});
router.post('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:'Changes Updated'});
});
Expected-Outcome:
Once the post request with all the details are sent, the <div id="res"> should contain the text Changes Updated.
Actual-Outcome:
Once the post request is sent, 200 OK response is observed and the response packet has the text Changes Updated. However, the browser does not reflect it. The new response received is not rendered.
Kindly assist in resolving this issue, as I'm fairly new to this( And the entire code is put together from a lot of places ). Also, any extra information, or good reads on the subject would be much appreciated

You will need to use the jQuery html attribute to insert the desired results into the div. ejs is used for creating templates before your page has loaded, and not for inserting ajax data after the page has loaded.
Try this:
$(document).ready(function() { //the jQuery equivalent
var form = $('#test');
form.on('submit', function(e) {
e.preventDefault();
var json = toJSONString(this);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(data) {
console.log(data);
$('#res').html(data); //insert "data" into the inner html of the div
},
dataType: "json",
contentType : "application/json"
});
}, false);
});
});

Related

Different Form Submit Actions for Different Forms

Super basic javascript question incoming...
I have two forms, one for uploading a file and one for providing text. I want to have a unique submit action for each of these forms. For the former, to upload the file, and for the latter, to serialize the form into JSON and POST it.
To attempt to accomplish this, I have one function called submit and another called submit2. The file upload form, which invokes submit works just fine.
The problem is with the second form, which invokes submit2. In particular, when I load the page, I get the following errors:
Query.Deferred exception: undefined is not a function (near '...$('form').submit2...').
TypeError: undefined is not a function (near '...$('form').submit2...')
Here's my HTML.
Upload an image
<form method="POST" enctype="multipart/form-data" action="upload">
<input id="img" name="file" type="file" accept=".jpeg,.jpg,.png">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Paste a URL
<form method="POST" name="urlForm" onclick="submit2()">
<input id="imgurl" name="url" type="text">
<input class="btn btn-primary" value="Submit">
</form>
And here's my javascript.
function ConvertFormToJSON(form){
var array = jQuery(form).serializeArray();
var json = {};
console.log(array)
jQuery.each(array, function() {
json[this.name] = this.value || '';
});
return json;
}
$(document).ready(function () {
var $status = $('.status');
$('#img').change(function (event) {
var obj = $(this)[0];
console.log(obj)
$status.html('');
if (obj.files && obj.files[0]) {
console.log(obj.files)
var fileReader = new FileReader();
fileReader.onload = function (event) {
$('.img-area').html(
`<img class='loaded-img' src='${event.target.result}' style="width:500px;height:500px;"/>`
);
}
fileReader.readAsDataURL(obj.files[0]);
}
});
$('#imgurl').change(function (event) {
var obj = $('#imgurl').val()
console.log(obj)
$('.img-area').html(
`<img class='loaded-img' src='${obj}' style="width:500px;height:500px;"/>`
);
});
$('form').submit(function (event) {
event.preventDefault();
var imageData = new FormData($(this)[0]);
console.log(imageData)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: imageData,
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
$('form').submit2(function (event) {
event.preventDefault();
var json = ConvertFormToJSON($('form'))
console.log(json)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json),
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
});
Edit: Added the ConvertFormToJSON function for completeness, although I think that's orthogonal to the issue I'm facing.
Problem in there Jquery Object dont have submit2 method and when you want to access submit2 method this is return undefined and when call this is return undefined is not function.

Sending form data and action to wordpress admin-ajax.php

I have a form that I want to send its data to admin-ajax:
<form method="POST" id="form">
<input type="text" name="name">
<input type="number" name="phone">
<input type="email" name="email">
<textarea name="overview"></textarea>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Javascript/jQuery code to send the data using Ajax:
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var form_data = $('#form').serialize();
$.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: form_data + {action: 'my_action'},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
Also tried formData:
var form_data = new FormData();
form_data.append('form', $('#custom').serialize());
form_data.append('action', 'my_action');
How to send the form data and the action my_action?
you need to change this line from data: form_data + {action: 'my_action'}, to data: {action: 'my_action', form_data:form_data},
jQuery(document).on("click","#submit", function(){
e.preventDefault();
var form_data =jQuery('#form').serializeArray();
jQuery.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: {action: 'my_action', form_data:form_data},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
and change input type submit to button.
In general i prefer to use this way, like in your case you are using submit type button:
$(document).on('click', '#submit', function(){ // the id of your submit button
var form_data = $('#your_form_data_id'); // here is the id of your form
form_data.submit(function (e) {
var my_action = "my_action";
e.preventDefault();
$.ajax({
type: form_data.attr('method'), // use this if you have declared the method in the form like: method="POST"
url: form_data.attr('action'), // here you have declared the url in the form and no need to use it again or you can also use the path like in your code
data: form_data.serialize() +'&'+$.param({ 'my_action': my_action}), // here you are sending all data serialized from the form and appending the action value you assing when declare var my_action
success: function (data) {
// after the success result do your other stuff like show in console, print something or else
},
});
});
});
Hope it helps you. if anything is not clear feel free to ask, i try to explain in the comments.
You should just pass form to new FormData() so in your case when submitting the form just pass new FormData(e.target);
Hope it helps

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Access Wikipedia API JSON data in jQuery

$('#searchButton').click(function(){
var searchInput = "";
searchInput = document.getElementById('test');
if(searchInput.value !== ""){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch='+searchInput+'&utf8=', function(json){
alert(json.query.search[0].title);
});
}
});
I'm confused on why the Json doesnt seem to be loading into the page. It seems like the whole operation stops at the url as even if i enter a string into the alert it doesn't run either...
You got this error because CORS is not enabled for the origin from which you are calling the mediawiki and you can check the same more about here.
https://www.mediawiki.org/wiki/Manual:CORS
You can use jQuery jsonp request as below with dataType: 'jsonp' instead.
Working snippet:
$(document).ready(function() {
$('#searchButton').click(function(){
var searchInput = "";
searchInput = document.getElementById('test');
if(searchInput.value !== ""){
$.ajax( {
url: 'https://en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: searchInput.value
},
dataType: 'jsonp'
} ).done( function ( json ) {
alert(json.query.search[0].title);
} );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="button" id="searchButton" value="Search" />

AutoComplete in jQuery with dynamically added elements

My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.

Categories

Resources