ajax response not as intended - ajax

The ajax call is established successfully. But when i try to get some response from the php there is a problem. In the .php file i have, <?php echo 'hello'; ?>. When i alert the parameter in the success function, it gives me the entire php file. The datatype requested in the ajax call is "text". Please let me know where i am making a mistake..
Code:
<script>
$(document).ready(function()
{
/* Attach a submit handler to the form */
//$("#foo").submit(function(event) {
$('form').on('submit', function(event){
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "ajaxSamplephp.php",
type: "post",
data: values,
datatype: "text",
success: function(data){
alert("success");
$("#result").html('Submitted successfully');
alert(data);
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
</script>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<div id="result">RESULT</div>
</body>
PHP File
<?php
echo 'Hi I am some random';
?>
OUTPUT: <?echo 'Hi I am some random'; ?> in alert window
GOT THE OUTPUT: My URL was the problem. I use wamp server and Eclipse PDT. The workspace was there in a different location so i coulnt get the output.
And in php file i have given echo json_encode('[{"key":"value"}]'); In the ajax call, i have changed the data type to 'json'. But alerting like alert(data.key); gives me 'undefined' - message. Help would be greatly appreciated...

UPDATE (to answer second part of question): Do JSON.parse(data) to generate a JavaScript object from your JSON. Then you can use the object returned by the method to get the properties.
I'd check to see that your web server is configured to use PHP.
This could mean you have to install the PHP package (using something like sudo apt-get install php5) or enable PHP in your web server's configuration (I believe the libapache2-mod-php5 package on Ubuntu configures it for you).

Related

Django template not re-rendering on successful AJAX get request

I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was successful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again.
My view:
def test(request,id=1):
return render(request,'test.html',{'num':id,'next':9})
My template and ajax code:
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(){
console.log('done');
}
});
}
</script>
Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change.
You're mixing server side rendering (DTL) and client side (javascript). Once django as rendered the template, you're javascript has no access to server side variable as {{ text }}.
You will have to do :
Template before SSR
<div id="content">
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data);
}
});
}
</script>
Template after SSR (something like this, you get the point)
<div id="content">
<p>66</p>
<button onclick='test(66)'>Test</button>
</div>
<script>
function test(next){
$.ajax({
url:'/test/'+next,
type: 'GET',
success: function(data){
document.querySelector('#content p').innerHTML(data)
}
});
}
</script>

How to pass hidden values using AJAX to another PHP file using GET method?

I’m trying to pass a hidden value that is from database to another PHP file using AJAX with GET method. But it keeps saying undefined variable. I couldn’t use a normal POST method as requirements do not want a button but a normal url link.
<script type="text/javascript">
$(document).ready(function() {
$("#edit").click(function(){
$.ajax({
type:"GET",
url:"editItem.php",
data:"itemid=" + $(this.find(":selected").val()),
cache: false,
success: function(msg){
}
});
});
});
</script>
<input type="hidden" name="itemid" id="edit"/>
Edit

Node.js + Express: Upload a file without reloading page

I am creating a chat application using Node.js, and would like to have a file upload feature. While I can get the file uploaded, the browser would always be redirected to another link or page refreshed, and this of course disrupts the chat.
First I tried using Express to do it:
index.html:
<form id="fileSendButton" action="/" method="post" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
app.js:
app.post('/', function(req, res){
//some validation and rename file
res.send();
return false;
});
Next I tried using AJAX, but still couldnt do it, whenever the AJAX POST to the Node.js server, it would reload the page. My AJAX code anyway:
index.html:
$.ajax({
type: "POST",
url: "/",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("chatText").innerHTML = res;
}
});
return false;
Third I went to look at Uploadify, but didnt want to add Flash dependancy to my site, so I didnt implement it.
Anyone can help me please? I dont want a page reload when a file is uploaded.
You can do it with a dynamically created hidden frame on the client side.
see here for a detailed howto with expressjs.
Uploadify now has a pure HTML5 play.

Jquery ajax call not working with relative and absolute urls

This is the code, I don't get any alerts whether, error or success. That ajax call returns a json map, and that map is populated in the select options dynamically.
<body>
<script>
$(document).ready(function() {
var selectValues;
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/",
data: APP_002,
async: false,
success: function(data) {
selectValues = data;
alert("Details saved successfully!!!");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
</script>
<div>
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
</div>
<div>
<select class="model"></select>
<a id="download-link"> Download </a>
</div>
</body>
Why it can't it send the request to the server, I'm using logs in the server side. No request there.
The page url : http://59.163.254.24:4287/wap/download/
Ajex request Url : http://59.163.254.24:4287/wap/retrieve/hanset/data/
I used both /wap/retrieve/hanset/data/ and http://myhost.com/wap/retrieve/hanset/data/ as the parameter for url in the ajax method, both are not working.
Code on your server (link you provided) is not the same as the one you have posted in your question. Code there has error: SCRIPT1009: Expected '}' meaning that you are missing } from your javascript.
Line:
// bonus: how to access the download link
comments out the rest of javascript as you have not switched it to a new row. This commented js includes some code and closing braces. You should add newline after this comment.
This is why you have javascript error and your browser never calls server.
And your parameter should be 'APP_002', not just APP_002
When you fix this, you will probably be able to make request, but if not, we can check for any other errors when you do this.
I think the problem is you're passing APP_002 using the data parameter, which is equivalent in this case to the querystring. Looking your comments on the OP, you need to actually pass it in directly in the URL so that the request is routed correctly on the server, like this:
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002",
async: false,
// rest of your code...
});
Example:
http://59.163.254.24:4287/wap/retrieve/hanset/data/?APP_002 -> page not found
http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002 -> JSON response
Actually, there is not a problem with the code you provided.
Here is jsfiddle:
http://jsfiddle.net/fHtcc/1/
However, there must be an issue with APP_002 (if it is not something defined) or Jquery is not included to page.

I have confused about the use of jquery ajax ,what's wrong with my code?

I just begin to learn jquery ajax framework here is my first attempt:
<div>
<input id="ajax" type="button" value="Read" />
</div>
also the js code:
$("#ajax").click(function () {
$.ajax({
type: "get",
url: "http://www.111222333444555.com",
//url: "http://www.google.com"
// timeout: 2000,
success: function () {
alert("ajax success!");
},
error: function () {
alert("ajax failed!");
}
});
});
abviously the "http://www.111222333444555.com" is not accessible,so I consider that resault is alert the "ajax failed!", but the resault is that the success function be executed,which alert "ajax success!"
then I change the url to "http://www.google.com",it alert "ajax success!" as well,
why the accessible url could cause the success function ?how can I escape the situation?I want when the url is not accessible,it will auto execute error function?How the $.ajax exactly works?
Please help me , thank you very much
Using the built-in objects, you cannot use Ajax to request a page that is outside of your page's domain.
There are solutions however...

Resources