How to use ajax in PHP foreach? - javascript

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
}

Related

The jQuery AJAX and PHP not fetching data values

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.

Form/button stop work after ajax partly reload page after form success

(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});

parsererror SyntaxError: Unexpected end of JSON input

When I add if(isset($_POST['uplprofimg'])), I get the error:
parsererror SyntaxError: Unexpected end of JSON input
If I exclude the php if isset post function, the code works perfectly.
So, PHP:
if(isset($_POST['uplprofimg'])){ //← This if broke my code >:(
//Works if I remove the ↑
if($_FILES['imagefile']['size'] > 5242880){
$ress = "<div class='error'>Max file size is 5MB</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$imgtype = pathinfo($_FILES['imagefile']['name'],PATHINFO_EXTENSION);
if(!in_array($imgtype,array('jpg','jpeg','png','gif'))){
$ress = "<div class='error'>Only <b>jpg</b>, <b>jpeg</b>, <b>png</b> and <b>gif</b> files are allowed (".$imgtype.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$newimgname = "/profile_picture/".random_num($length = 8).time().random_num($length = 8).".".$imgtype;
$newimgnameserv = $_SERVER['DOCUMENT_ROOT'].$newimgname;
if(move_uploaded_file($_FILES['imagefile']['tmp_name'],$newimgnameserv)){
$upuser = $mysqli->prepare('UPDATE accinfo SET profilepic = ? WHERE username = ?');
$upuser->bind_param('ss',$newimgname,$username);
$check = $upuser->execute();
if($check == true){
echo json_encode(array('response' => true));
}else{
$ress = "<div class='error'>SQL Error</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}else{
$ress = "<div class='error'>Couldn't move the file. Please try again later.(".$newimgname.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}
}
}
and JS:
$("#uploadimgform").on("submit",function(event){
event.preventDefault();
var formData = new FormData(this);
$("#uploadlistener").html("<img src='/images/load.gif' width='50px' />");
$.ajax({
type: 'POST',
url: "/system/requests.php",
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.response === true){
$("#bodyfader").fadeOut("slow");
$("#expandedupl").fadeOut("slow");
$("#uploadlistener").html("");
}else{
$("#uploadlistener").html(data.ress);
$('#profilepic').css('background', 'url(/images/defaultprof.png)');
$("#profilepic").css("background-size","cover");
$("#profilepic").css("background-position","center");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
If I remove the if(isset($_POST['uplprofimg'])){...}, the code works. But if I add it there, I get the json error. What is going on?
HTML Form:
<form method='POST' enctype="multipart/form-data" id='uploadimgform' style='display: none;'>
<input type='file' id='upload' name='imagefile' accept="image/x-png,image/gif,image/jpeg" />
<input type='submit' id='uploadconf' name='uplprofimg' />
</form>
This is how the form is submitted:
$("#upload").change(function(){
if(this.files[0].size > 5242880){
$("#uploadlistener").html("<div class='error'>Maximum file size is 5MB.</div>");
$("#upload").val("");
}else{
$("#uploadimgform").submit();
readURL(this);
}
});
I have no idea why, but I did this:
formData.append('uplprofimg',1);
and the code works. Someone can explain this?
I think the issue here is that you are using FormData to send the submit button value to the server.
The submit element is not added to the entries.
I have not found clear details in the submit specification or in the construction of the formData.
Indeed, when running this snippet we can see that the submit value is not appended to the FormData.
var formData = new FormData(document.querySelector('#myForm'));
for (var p of formData.entries()) {
console.log(p[0] + " " + p[1]);
}
<form id="myForm">
<input type="text" name="sometext" value="This is submitted" />
<input type="submit" name="Submit" value="someSubmitValue" />
</form>
I would suggest you to use a hidden input if you need to send some additional data that is not part of the displayed input elements.
You need to set the upload_max_filesize option in the php.ini file.
The default max size is 2M. You need to set a higher value:
upload_max_filesize = 32M

create form dynamically and submit it

So I have a jQuery plugin I wrote below, in plugin.js. I want to be able to also submit the form via JSON/AJAX every time it's created.
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
$('#form').submit(function(e)
{
var postData = form.find('form').serializeArray();
if(postData.name === "someREGEXstring" || postData.email === "someREGEXstring") {
console.log("empty inputs not cool");
}
var formURL = $('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
$('#form').submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
in HTML view
<div id="newForm"></div>
<script>
$(document).ready(function(){
$("#newForm").create();
});
</script>
Is this the correct way to make this or should I:
Create a another namespace under the same file for the AJAX portion
Create another namespace under a different file the AJAX portion
If the question is purely about how to arrange the code, I would suggest you pull the form template out of the code completely and make your plugin more flexible.
Option 1. Create the form as a template in the page and pass the
template selector to plugin as an option
Option 2: Pass the template to your plugin
Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/
Template in HTML:
<script id="template" type="template">
<div id="form" class="container">
<div>User Login</div>
<form action="/create/one" method="post"/>
<input type="text" name="name" placeholder="name"/>
<input type="email" name="email" placeholder="email"/>
<button type="submit">Login</button>
</form>
</div>
</script>
Create with:
$(document.body).create('#template');
And plugin simplified to:
(function ( $ ) {
$.fn.create = function(template) {
form = $($(template).text());
form.submit(function(e) {
// This is the actual form object now
var $form = $(this).find('form');
// Test contents of form here
// If values are correct proceed with Ajax call
var postData = $form.serializeArray();
var formURL = $form.attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); // Stop default action
});
return this.append(form);
};
}( jQuery ));
Now your plugin code will work with any form.
Based on your comment I have removed the automatic submit of the form, as that made no sense
This should work:
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
form = $(form);
form.submit(function(e) {
var postData = form.find('form').serializeArray();
var formURL = form.find('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
form.submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
Here is a demo in JSFiddle.
What is fixed:
form = $(form) is used in order to create the DOM elements based on the form string.
Change the way postData, formURL are initialized.
<div id="#newForm"></div>
should be
<div id="newForm"></div>
to load this form element
I have some chages, like:
$('#form').submit(function(e) should be $(form).submit(function(e) as variable form contains all the HTML of form wrapped within DIV.
in the submit of form, $(this) will refer to the form element itself.
Here is the modified code:
(function ($) {
$.fn.create = function () {
var formContainer = $("<div />", {
id : "form",
class : "container"
}).append("<div>User Login</div>");
var form = $("<form />", {
action: "/create/one",
method : "post",
submit : function(e){
var actionUrl = $(this).attr("action");
alert(actionUrl); // just to check if this is working or not
$.ajax({
url : actionUrl,
type : "POST",
data : $(this).serializeArray(),
success : function (data, textStatus, jqXHR) {},
error : function (jqXHR, textStatus, errorThrown) {}
});
e.preventDefault();
}
})
.append('<input type="text" name="name" placeholder="name"><input type="email" name="email" placeholder="email"><button type="submit">Login</button>')
.appendTo(formContainer);
return this.append(formContainer);
};
}(jQuery));
$("#test").create();
HTML for testing:
<div id="test"></div>
JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/
I have created the HTML nodes via jquery instead of just HTML string. attaching events to nodes is easier than converting string to HTML first and then attaching event to them. Hope you like it.

No Data Posted in a form

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?

Categories

Resources