Convert jQuery Object to String upon AJAX call - javascript

Let's say I submit a form with anything in the value of user_input like "I am free." I submit it through AJAX and it gets returned to me as a string. Ok now it's an Object... how would I turn that into a string?
Thank you,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<title>Sin título 3</title>
</head>
<body>
<div id="result_target" style="display:none;"></div>
<form id="form_to_post" action="#" method="post">
<input type="hidden" name="url" value="example.php" />
<input type="text" name="user_input" />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#form_to_post").submit(function() {
var hiddenURL = $("input[name=url]");
var userInputForm = $("input[name=user_input]");
//var dataString = "userInput="+inputForm;
$.ajax({
type: "POST",
url: hiddenURL;
data: {userInput: userInputForm},
success: function(return_contents) {
//returns jquery object...
var output =//
$("#result_target").html(output);
}
});
});
});
</script>
</body>
</html>

use val() to get values from inputs
data: {userInput: userInputForm.val()},

Related

jQuery get function doesn't work as expected

I need to get photos using GIPHY API, I have the following function:
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="submit" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>
So, the problem is that $.get() function doesn't respond at all, even always() callback function does not get executed.
When I try this particular URL in the Postman application, I get the response (json object) and I can access the data.images.origianl.url property it is there.
When I try the following line of code in the console :$.get("https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1"); I get the response with the status code 200, so it should work in the main.js file, but in my case it doesn't.
I have two variables url1 and url2 this is because, in my first tries I did not get anything with the url1, but getting the success with the url2. After some time I didn't get anything using two of them.
What is the problem? How can it be that I can get responses from Postman and from the console using the same URLs, but do not get them with actual code?
Thank you for your patience!
This is a common problem, understanding the difference between type button and type submit.
Submit will submit the form. Whereas button will just process the event handlers assigned.
Change
<input type="submit"
to
<input type="button"
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="button" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>

Ajax script is not updating PHP file and his var value

This is simple form, on click i need calculated value to be displayed in file process.php, but this is not working for me. It seems that "click" on "=" don't do anything, in process.php there is default value "0", no results.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="//code.jquery.com/jquery-1.12.0.min.js">
$('#button').click(function() {
var val1 = $('#text1').val();
var val2 = $('#text2').val();
$.ajax({
type: 'POST',
url: 'demo/process.php',
data: { text1: val1, text2: val2 },
success: function(response) {
$('#result').html(response);
}
});
});
</script>
<input type="text" id="text1"> +
<input type="text" id="text2">
<button id="button"> = </button>
<div id="result"></div>
</body>
</html>
AND PHP
<?php
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
echo $text1 + $text2;
?>
first of all, are you using a php server?
if you do then try this (yes i used a different library):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" id="text1" />
<input type="text" id="text2" />
<button type="button" id="button"> = </button>
</form>
<div id="result"></div>
<script type="text/javascript">
$('#button').click(function() {
var val1 = $('#text1').val();
var val2 = $('#text2').val();
$.post( "demo/process.php", {text1: val1, text2: val2} , function(data){
$('#result').html(data);
});
});
</script>
</body>
</html>
in php:
<?php
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
echo $text1 + $text2;
?>
Tip: Always specify the type attribute for a element. Different browsers use different default types for the element.

Javascript to load page not working

I'm trying to get text from a text input, append it to a URL, and go to that URL, using Javascript. But when I submit, it appears to just reload the page.
http://jsfiddle.net/E3vv6/
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
}
</script>
</head>
<body>
<form onsubmit="loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>
You need to use event.preventDefault() in the submit function.
Live Demo (click).
Further, inline js (onsubmit in your html) is bad practice for a lot of reasons. Here are some: https://www.google.com/search?q=Why+is+inline+js+bad%3F
If would be better to get a reference to the form with javascript and attach the event listener.
<form id="myForm">
<input type="submit" value="Submit">
</form>
JavaScript:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e) {
myFunction();
e.preventDefault();
});
function myFunction() {
console.log('submitted!');
}
You need to prevent the default behaviour of the onsubmit.
You could use return false:
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
return false;
}
</script>
</head>
<body>
<form onsubmit="return loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>

how to submit a form from loaded form into main page?

contact.php
... html form ...
$('#submit').click(function(){
$.post("mail.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
mail.php is a separate file (for sending mail), and everything works in this arrangement.
But I need to load contact.php into index.php
$('#divR').load('chapters/contact.php');
so corresponding js line becomes
$.post("chapters/mail.php", $("#contact").serialize(), function(response) {...
Submitting the form in this case response from mail.php is received, but POST array is empty, i.e. form doesn't send any data to mail.php !?
I wrote your code in 2 new pages to see what it actually does, and noticed a few things. A few small things such as calling the submit handler instead of click, since people can also press Enter to submit a form, but most important the data itself: A form doesn't need to be serialized, the browser will already do that for you. In this script I store the data in a new object and pass it to the $.post method.
<form method="post" action="" id="contact">
<div>
<input id="email" type="text">
</div>
<div>
<input id="submit" type="submit">
</div>
</form>
Script:
$("#contact" ).on("submit", function () {
var data = {
email: $("#email").val()
};
$.post("test.php", data, function (response) {
$('#success').html(response);
});
return false;
});
In test.php I simply do a print_r($_POST), which is also the response. It will output something like:
Array
(
[email] => test
)
Hope this helps.
I've made a simple test, trying to mimic your goal:
testLoad.php = index.php in your case:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
$('#testLoad').load('Test/testForm.php');
});
</script>
</head>
<body>
<div id="testLoad"></div>
<div id="success"></div>
</body>
</html>
testForm.php and testTarget.php are respectively - contact.php and mail.php and are situated in folder Test their code is as follows:
testForm.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form id="contact" method="post" action="">
<p>
<label for="textfield">Name:</label>
<input type="text" name="textfield" id="textfield">
</p>
<p>
<label for="textfield2">Address:</label>
<input type="text" name="textfield2" id="textfield2">
</p>
<p>
<label for="textfield3">Mail:</label>
<input type="text" name="textfield3" id="textfield3">
</p>
<p>
<label for="textfield4">Subject:</label>
<input type="text" name="textfield4" id="textfield4">
<br>
</p>
<p>
<label for="textarea">Message:</label>
<textarea name="textarea" id="textarea"></textarea>
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" onClick="sendForm();">
</p>
</form>
<script>
$('#submit').bind('click', function(){
//console.log($("#contact").serialize());
$.post("Test/testTarget.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
</script>
</body>
</html>
and testTarget.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php print_r($_POST);?>
</body>
</html>
when testing in success div I receive the POST printed out.
Hope this helps.

jQuery/AJAX execution of PHP not working

I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?
Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code

Categories

Resources