I am trying to fetch the values of the data variable passed with jQuery AJAX to a php page. How to solve it?
Below is the HTML page code:
<input id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>
On the button click this jQuery AJAX calls a php page:
$.ajax({
type: "POST",
url: "jquery-ajax-hello.php",
contentType: "application/json; charset=utf-8",
data: '{"name":"' + $("#name").val() + '"}',
success: function (result, status, xhr) {
$("#message").html(result);
},
error: function (xhr, status, error) {
$("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
The PHP Page code is:
<?php
$name = $_POST['name'];
echo "Hello ".$name.", How are you ?";
?>
In the php page I am not able to fetch the data varaible 'name' value?
Please help?
Your data should be an object, what you're passing is a string, so it should be
data: {
name: $("#name").val()
},
JQuery Ajax
Form data
<input type="text" id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>
Jquery section
$(function() {
$("#submit").click(function() {
var name = $('#name').val();
$.ajax({
url : 'success.php',
method: 'POST',
data : {name:name},
success : function(res) {
$('#message').append(res);
}
});
});
});
success.php
<?php
$name = $_POST['name'];
echo "Hello Mr ".$name ;
?>
change data property to
data: {name: $("#name").val() }
and it would work fine
change data to:
data: { name: $("#name").val() }
because data must be an object having key : value pair in it
In your case:
data: '{"name":"' + $("#name").val() + '"}'
{} is wrapped with single quotes. Remove them.
Related
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>
I'm sending an AJAX request with multiple arrays and I can't figure out how to grab the data?
This is what I'm sending:
I'm doing this through a jQuery AJAX POST to a PHP file.. How would one go about grabbing the data from here?
Thank you!
-- EDIT!!
This is the jQuery
var h1 = []
h2 = []
h3 = [],
layout = $( "input[type=radio][name='layout_option']:checked" ).val();
$("ul.widget-order[name='1'] li").each(function() { h1.push($(this).attr('id')); });
$("ul.widget-order[name='2'] li").each(function() { h2.push($(this).attr('id')); });
$("ul.widget-order[name='3'] li").each(function() { h3.push($(this).attr('id')); });
var sendData = JSON.stringify({
ids1: " " + h1 + "",
ids2: " " + h2 + "",
ids3: " " + h3 + ""
});
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: { data: sendData } + '&layout=' + layout,
success: function( data ){
$("#post_reply").html(data);
console.log( { data: sendData } );
)};
)};
To read the JSON encoded data on the PHP side:
<?php
$json = file_get_contents('php://input');
$decodedJSON = json_decode($json);
?>
http://php.net/manual/en/function.json-decode.php
$_POST['data'] contains JSON, so call json_decode().
$data = json_decode($_POST['data'], true);
Now you can access $data['ids1'], $data['ids2'], etc.
There isn't really any good reason to send the data as JSON. You could just put the original object directly in the jQuery data: option. Then you would could access the parameters as $_POST['ids1'], $_POST['ids2'], etc.
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: {
ids1: " " + h1,
ids2: " " + h2,
ids3: " " + h3,
layout: layout
},
success: function(data) {
$("#post_reply").html(data);
console.log({
data: sendData
});
}
});
Assuming that the post request to your Php file is successful you can access it by using the $_POST variable.
If I may, I would recommend changing the way you are making the jQuery request to the following:
var h1 = []
h2 = []
h3 = [],
layout = $( "input[type=radio][name='layout_option']:checked" ).val();
$("ul.widget-order[name='1'] li").each(function() { h1.push($(this).attr('id')); });
$("ul.widget-order[name='2'] li").each(function() { h2.push($(this).attr('id')); });
$("ul.widget-order[name='3'] li").each(function() { h3.push($(this).attr('id')); });
var sendData = JSON.stringify({
ids1: " " + h1 + "",
ids2: " " + h2 + "",
ids3: " " + h3 + ""
});
var sPayload = "data=" + encodeURIComponent(sendData) + "&layout=" + encodeURIComponent(layout);
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: sPayload,
success: function( data ){
$("#post_reply").html(data);
console.log( { data: sendData } );
}
});
There were a few syntax errors in code you posted which I have corrected in the code included in my answer, but most importantly, I have modified your data to being all of one encoding. It seems like you were trying to combine a JSON Object with standard data encoded as application/x-www-form-urlencoded. I have standardized this in the code above so all data is posted as application/x-www-form-urlencoded.
In your PHP, you can then access this as:
<?php
// First, let's get the layout because that's the easiest
$layout = (isset($_POST['layout']) ? $_POST['layout'] : NULL);
// As a note, the isset(...) with ternary operator is just my preferred method for checking missing data when extracting that data from the PHP super-globals.
// Now we'll need to get the JSON portion.
$jData = $_POST['data'];
$data = json_decode($jData, $assoc=true);
echo "ids1 is " . $data['ids1'] . "\n<br>\n";
echo "ids2 is " . $data['ids2'] . "\n<br>\n";
echo "ids3 is " . $data['ids3'] . "\n<br>\n";
?>
Follow this code
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
I think have a mistake between data is property of ajax object and data is property in your post data.
Please post your jquery code.
I used ajax for my current project with laravel and i try to pass value of textbox using ajax but it pass R every time, even if i pass the wrong variable with ajax. my code is as below
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="total_amount" value="123" name="total">
</div>
javascript code
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: {
lists: list, total: total, "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
laravel method
public function getTotal(Request $request)
{
$list = #$request['lists'];
$total = #request['total'];
return $total;
}
varibale list work fine but total always return value R, when it print first time log that time it print correct value in console, but second time in success function of ajax it print always R. where i made mistake??
Change this:
$total = #request['total'];
to this:
$total = #$request['total'];
^
Try like below:
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: "lists="+list+"&total="+total+"&_token={{ csrf_token()}}",
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}
I use a form which sends data with a POST method to a php file via AJAX. Everything is ok and I can see the results in the html table in its id div name. But now this very same table contains input fields (second form) with the same method. All ids and names are different, I can see the fields values with
alert( $("input[name=id]").val() );';
Am I missing something ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form name="ajaxform" id="ajaxform" action="edit.php" method="POST">
<select name="user" id="simple-post" onchange="this.value.submit()">
<option value="">Select a person:</option>
<option value="0">John</option>
<option value="1">Peter</option>
<option value="1">Heinrich</option>
</select>
</form>
<div id="simple-msg">
</div>
<script>
$(document).ready(function()
{
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
</script>
</body>
Now the edit.php page
<?php
$json_a=json_decode(json_encode($_POST),true);
$output=array();
$i=0;
foreach ($json_a as $key => $value){
echo $key . ':' . $value; // peut-ĂȘtre branchĂ©!
$output[$i]= $value;
$i++;
}
$array_user=array();
$array_user[0]=$output[0];
$array_user[1] ="Yes";
$array_user[2] ="mypass";
echo '<form name="ajaxform1" id="ajaxform1" action="SQL_user.php" method="POST">
';
echo '<input type="text" name="id" size="3" value="' .$array_user[0]. '"/>';
echo '<input type="text" name="online" size="3" value="' .$array_user[1]. '"/>';
echo '<input type="text" name="password" size="20" value="' .$array_user[2]. '"/>';
echo '<input type="button" id="simple-post1" value="Apply" />';
echo '</form>';
echo '<br>';
echo'<div id ="simple-msg1">';
echo'</div>';
echo '<script>
$(document).ready(function()
{
$("#simple-post1").click(function()
{
$("#ajaxform1").submit(function(e)
{
$("#simple-msg1").html("<img src='."'loading.gif'".'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint"'.">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)".'"
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint">AJAX Request Failed<br/> textStatus='."'+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
});
".'$("#ajaxform1").submit();
});
});
</script>';
?>
The second form doesn't work...
you have put the following code to run if an element with id=simple-post gets clicked. notice, .submit is nested inside .click
$(document).ready(function () {
$("#simple-post").click(function () {
$("#ajaxform").submit(function(e){
//code to execute on submit action goes here
}
$("#ajaxform").submit(); //SUBMIT FORM
});
});
so the EventHandler on form submit will registered ONLY AFTER an element with id=simple-post gets clicked which is the reason, ajax request is not happening & form gets submitted normally.
Did you mean the following:
$(document).ready(function () {
$("#ajaxform").submit(function (e) {
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code
class="prettyprint">' + data + '</code></pre>');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#simple-post").click(function () {
$("#ajaxform").submit(); //SUBMIT FORM
});
});
The above code will set EventHandler on form submit on $(document).ready. The form will get submitted via ajax/xhr either when:
Submit button form is pressed.
An element with id=simple-post gets clicked.(Run Code button)
Is this what you intend on doing?