how to get php response by using ajax - php

In a html web page, i want PHP response show in <span>..</span>.
Can anyone tell me how to do it or what's wrong with other codes?
thanks~~ ^^
web code:
<html>
<head>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
//dosomething.....
},
});
});
</script>
</head>
<body>
<form method="post">
<input id="submit" type="button" value="next">
</form>
<br><br><span id ="status"></span>
</body>
</html>
php code:
<?php
echo ("success");
?>

After you get the response do the following
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
$("span#status").html(data);
},
});
});

This won't work as the datatype provided won't be JSON... the dataType attribute in jQuery must match the type of data you send using PHP.
To get it working with a simple "success" message, you may do :
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'html',
success: function(data) {
$("span#status").html(data);
},
});
});

Because you use dataType: "json", the AJAX function thinks it's getting a JSON array. But since you only respond with "succes" in your php, it will not parse as JSON.
You should JSONify your output in PHP with json_encode(), after that you can call the succes callback in ajax, or use the .done function;
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
$("span#status").html(data);
}
});
});
or with .done functionality:
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
}).done(function(data) {
$("span#status").html(data);
});
});
The .done function is better for readability and maintainability in my opinion.

Related

How to upload image through jQuery Steps

I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
Follow this way for upload an image, In this way you don't want HTML form.
Add this code to your mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
Then add this for upload.php
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#upload_doc").on("change", function() {
$("#imageUploadForm").submit();
});
});
</script>
From your comment,
actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.
If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
So your jQuery should be like this:
if(currentIndex == 0){
event.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response) {
console.log(response);
}
});
}
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});

How to check php is loaded when using AJAX

I use AJAX, and this work without problems, like this:
$('#main .left').load('top.php');
or this:
$.ajax({
type: "POST",
url: '/ajax_main.php',
data: "i=ajax_call",
success: function(msg){
console.log('ok');
}
});
// php side reprorts $_GET['i'] = "ajax_call";
When I set:
function periodicMethod(){
$.ajax({
type: "POST",
url: 'ajax_main.php',
data: "i=ajax_call",
success: function(msg) {
console.log('ok');
}
});
}
setInterval(periodicMethod, 1000);
The method is called and console.log reports "ok" any second. This looks like 'ajax_main.php' is loaded. But in the PHP file:
edit
echo '<script>console.log("php");</script>';
Does not give any results. The path in URL is ok. When I change it or remove 'ajax_main.php' from server, error is reported. What may be wrong?
edit
another version of php:
<script>
function ppp()
{ console.log('sss');
}
</script>
<?
echo '<script>ppp();</script>';
?>
is not working to
try this code
<script>
function periodicMethod(){
$.ajax({type: "POST",url: 'ajax_main.php',data: "i=ajax_call",
success: function(msg){ console.log('ok');
jQuery("#demo_data").html(msg);
}});}
setInterval(periodicMethod, 1000);
</script>
<html>
<body>
<form action="" method="post">
<input type="hidden" name="demo_data" id="demo_data"/>
</form>
</body>
</html>

I am trying to fetch json data's from .php file.php file i.e stored in server.I have writtened the following code.But I am unable to fetch data

I am new to this jquery and phonegap.I am finding little difficulty in parsing the data from .php file from a local server.Please help me in doing so.
This is my index.html page:
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parseJSON()
{
var json;
$.ajax({
type: 'POST',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
// data: $('#abc').serialize(),
dataType: 'json',
success: function(data){
alert(data);
$('#data').append(data);
}
});
}
</script>
</head>
<body onload="parseJSON()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>
The login.php file contains a sample json data's as follows:
{"username":"test#test.com","password":"password"}
If you are trying to get the data using php and ajax use jsonp,
in your PHP file add callback for json output:
echo $_GET['callback'] . '('.json_encode($data).')';exit;
apppend callback in your ajax call
Javascript:
$.ajax({
url: 'http://192.168.1.12/training/services/login.php?callback=?',
cache: false,
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
And last but not least, dont forget to add domain white list for your localhost
in corodova.xml:
<access origin="http://192.168.1.12"/> OR
<access origin="*"/> to allow all domains
If I have understand correctly you may do something like that.
If your php page send data to your html one, you may use GET instead of POST
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parse()
{
var json;
$.ajax({
type: 'GET',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
dataType: 'json',
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#data').html(obj["username"]);
}
});
}
</script>
</head>
<body onload="parse()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>

$.ajax( type: "POST" POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'

Sending data to php function from ajax

I am using an ajax call which is as follows
var ID=$(this).attr('id');
var input=$("#input_"+ID).val();
var dataString = {id: ID, value: input};
$("#span_"+ID).html(input);
if(input.length>0)
{
$.ajax({
type: "POST",
url: "/apps/worker_app.php",
data: dataString,
cache: false,
success: function(html)
{
$("#span_"+ID).html(span);
}
});
}
How can I get the data in my php function edit_ajax() which is inside worker_app
I use post but the array come to be empty
Thanks
Add dataType: 'json',
var ID=$(this).attr('id');
var input=$("#input_"+ID).val();
var dataString = {id: ID, value: input};
$("#span_"+ID).html(input);
if(input.length>0)
{
$.ajax({
type: "POST",
url: "/apps/worker_app.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(msg)
{
$("#span_"+ID).html(span);
}
});
}
and in worker_app.php get id and value by
$id=$_POST['id'];
$value=$_POST['value'];
edit_ajax($id,$value);
function edit_ajax($id,$value){
$sql="update from ..........";
}
Is this what u want?
Have you tried setting the dataType in your ajax call, like this:
$.ajax({
type:"POST",
url: "/apps/worker_app.php",
data: dataString,
cache: false,
success:function(html) {
},
dataType:"json"
});
Also, you could use a tool like firebug to see so the data is passed correctly in your ajax request.
Here is an example:
file1.php:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javscript"></script>
<script type="text/javascript">
$(document).ready(function() {
// catch submit event for your form
$('#form1').submit(function() {
// serialize data from form
var data = $(this).serialize();
$.ajax({
type="POST",
url:"file2.php",
data:data,
success:function(resp) {
// output response
$('#output').html(resp);
}
});
return false;
});
]);
</script>
</head>
<body>
<div id="output"></div>
<form method="POST" id="form1">
<input type="text" name="name" />
<input type="submit" value="send" />
</form>
</body>
</html>
file2.php:
<?php
if(isset($_POST['name'])) {
header('Content-type: text/html');
echo '<p>Response From Server - Your name is: '.$_POST['name'].'</p>';
}
?>
in /apps/worker_app.php get those posted values
$id=$_POST['id'];
$value=$_POST['value'];
and now use the values with your php function
function edit_ajax($id,$value)
{
echo $id;
echo $value;
}
echo $return=edit_ajax($id,$value);
now you can get the values in the current page as
success: function(html)
{
$("#span_"+ID).html(span);
}
> $.ajax({
> type: "POST",
> url: "/apps/worker_app.php",
> data: dataString,
> cache: false,
> success: function(msg)
> {
> $("#span_"+ID).html(msg);
> }
> });
on success, the argument function is receiving should be same used with
$("#span_"+ID).html(msg);

Categories