php array_push not appending the array after the ajax call - javascript

I am using ajax and php and i would like to append my array each an everytime i make an ajax call. But it is not working.
These are my codes:
$('#multiple_upload_form' +count).ajaxForm({
target:'#images_preview'+count,
beforeSubmit:function(e){
console.log("gud to go");
},
success:function(data){
console.log(data);
console.log("succeded");
},
error:function(data){
console.log("failde");
}
}).submit();
PHP this is the pHP side of it.Plase help
<?php
$questionArr = array();
if($_POST['image_form_submit']){
array_push($questionArr,$questionNum );
if(is_array($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response']= "exist";
echo json_encode($questionArr);
}else{
$response['response']= "question does not exist";
echo json_encode($response);
}
}
}else{
$response['response']= "not array";
echo json_encode($response);
}
}
?>
And this is my HTML
<form method="post"name="multiple_upload_form"id="multiple_upload_form" enctype="multipart/form-data" action="php_work/test.php">
<input type="hidden" name="image_form_submit" value=""/>
<input type="file" name="images[]" id="images" multiple >
</form>

It may help you:
<?php
$questionNum = 1; // Or from anywhere you are getting data into it
$questionArr = array();
$response['response']= "not array"; // Giving Default value
if($_POST['image_form_submit']){
$questionArr[] = $questionNum;
if(!empty($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response'] = "exist";
}else{
$response['response']= "question does not exist";
}
}
}
}
echo json_encode($response);
exit;
?>

First: There is one if statement in the PHP which won't return a value, since there's no else. So if $_POST['image_form_submit'] is false, nothing is echoed.
Second: array_push($questionArr, $questionNum); Where do you defined $questionNum in your PHP script?
Third: in your JS: $('#multiple_upload_form' +count) there you try to refer to an element with an id with a number I guess? I don't see such an element in your HTML. I also don't see in the JS code where you define count.
Long answer short: check both PHP and JS codes for errors.

Related

Javascript inside php not working

I've create a code that check if a variable is empty or not.
If the variable is empty I execute a javascript alert, in particular:
if($verbo_name == NULL)
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
If I insert a message inside the echo, the message appears correctly, but I want show the alert in javascript. What's the error? Thanks..
UPDATE more details:
$results = $con->query("SELECT verbo, descrizione FROM verbo WHERE verbo = '$verbo'");
$verbo_name = NULL;
while($row = $results->fetch_array())
{
$verbo_name = $row['verbo'];
}
Check below codes are working fine for me.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
?>
Check this one
if(empty($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
This should trigger an alert:
<html>
<body>
<?php
if($verbo_name == NULL)
{
$msg = enter code here'no record available in the database';
} else {
$msg = 'not set';
}
echo "
<script>
alert('". $msg ."');
</script>";
?>
</body>
</html>
If the message is not set the problem is just the variable.
This is Pravat Kumar Sahoo's answer,
This must work fine.
If you are testing on google chrome, you might have prevented the alert dialog message mistakenly. Please try clearing the cache/cookie or test on any other browser.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "<script>alert('no record available in the database');</script>";
exit();
}
?>
Update:
Instead of alerting the message inside PHP, echo a message, like "NoData". And in the ajax calling Javascript, receive response "success".
echo "NoData"; // In PHP file.
In your Javascript, get the response,
success:function(response)
{
if(response == "NoData");
{
alert("No data in the Database");
}
}

How do I debug Resource #6 error in MSSQL?

I have a pair of radio buttons and I want to insert its value into my database in the form of bit. Following is the HTML code for the same.
<form id="Form" method="post" class="overlay" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input type="hidden" id="Keyy" name="key" value="">
<label for="JRadioYes">Active? Yes</label> <input type="radio" id="JRadioYes" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "yes") echo "checked='checked' "; ?>value="yes">
<label for="JRadioNo">No</label> <input type="radio" id="JRadioNo" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "no") echo "checked='checked' "; ?>value="no">
<input type="submit" id="submitter" name="sub" value="Submit!" onclick="decider(this)">
</form>
The following is the PHP code for inserting into the database
// Check if radio is submitted
if (isset ( $_POST ["activeradio"]))
{
//Extract values from $_POST and store in variables
$select_radio = $_POST ["activeradio"];
if ($select_radio == "yes") {
$active_status = true;
//I also tried assigning 1 instead of true
}
if ($select_radio == "no") {
$active_status = false;
//I also tried assigning 0 instead of false
}
if($_POST["key"] == "update")
{
try
{
echo "<script type='text/javascript'>
alert('$active_status');
</script>";
$JobInt = intval($JobTypeID);
$stmt = sqlsrv_query ( $conn, 'EXEC spEditThisJobType #Active = ?', array (
$active_status
) );
}
catch(Exception $e)
{
echo "Error :". $e;
}
if($stmt != null)
{
echo "<script type='text/javascript'>alert('Successfully Updated!$stmt');
</script>";
}
}
}
I am able to get the alert which says Successfully Updated, but I am also getting Resource #6 error along with it. Also the database does not get updated.
What is the mistake I have done here? Please guide me. Thank you in advance.
Have a look at the documentation for sqlsrv_query - it returns a resource object, not the result of the query.
Therefore when you echo "Successfully Updated!$stmt", the resource $stmt is converted to its string representation - Resource #6.
So you either need to remove $stmt from your echo, or do something with the resource such as reading the data using sqlsrv_fetch_array.

Adding php within a php code

Basically what i mean is i want to echo a piece of a php using a php method code below is getting errors
<?php
$myString = '<?= $_GET['content'] ?>';
echo $myString;
?>
maybe theres a javascript alternative?
full code below
<?php
if (in_array($_GET['content'], array(tree, 3, 4, 5)) ) {
$myString = "<?= $_GET['content'] ?>";
$myParsedString = htmlentities($myString);
echo $myParsedString;
}
else {
echo "nothing to see here";
}
?>
you can directly access $_GET inside <?php ?>no need to use tag again inside :try this.
$myString = $_GET['content'];
This should work for you:
if ( in_array($_GET['content'], array("tree", 3, 4, 5)) ) {
$myString = $_GET['content'];
echo $myParsedString = htmlentities($myString);
} else {
echo "nothing to see here";
}
No need to use another PHP tag inside PHP tag. Simply can try this
<?php
if (in_array($_GET['content'], array('tree', 3, 4, 5)) ) {
$myString = $_GET['content'];
$myParsedString = htmlentities($myString);
echo $myParsedString;
}else {
echo "nothing to see here";
}
?>
Just escape the PHP code you get and then u can echo it
$myString = mysql_real_escape_string('<?= $_GET['content'] ?>');
echo $myString;
I hope that helps

jquery $.post not working unless debugging

I have simple form for updating the stock of products, it uses datatables to generate rows for all the items in the database. I can update the stock correctly using the form when I set a break point in the function, but if I remove the break point it stops working.
HTML form:
<form id="updateStock">
<input id="Penguincard" type="text" value="200">
<input type="submit" onclick="updateStock("Penguincard", "Penguin card");" value="Update">
</form>
Javascript:
function updateStock(id, item){
var idS = "#" + id;
var newStock = $(idS).val();
$.post("URL",{item: item, stock: newStock},
function(result){
alert(result);
});
return false;
}
PHP:
<?php
ini_set('display_errors', 1);
// Adds a new item to the database
require('common.php');
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["item"])){
echo 'item is blank';
exit();
}else
{
$item = test_input($_POST["item"]);
// check if item only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$item))
{
echo 'item reg';
exit();
}
}
if (empty($_POST["stock"])) {
echo 'stock is blank';
exit();
}else
{
$stock = test_input($_POST["stock"]);
// check if stock only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$stock))
{
echo 'stock reg';
exit();
}
}
}else{
//don't run unless post
echo 'Not post';
exit();
}
$stmt = $db->prepare('UPDATE `stock` SET `stock`=:stock WHERE `item`=:item');
// bind the parameters to the insert after sanitizing them
$stmt->bindParam(':item', $item);
$stmt->bindParam(':stock', $stock);
//execute the insert
$status = $stmt->execute();
if( $status ){
echo 'Item added successfully!';
exit();
}
//sanitizing function
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
EDIT: by not working I mean it seems to run the onClick function but doesn't submit the post.
From the answers it seems that debugging was allowing the post to be submitted before the default form action occurred, therefore making it working.
You're never actually suppressing the click functionality of the submit button; you return false; from the updateStock function, but that doesn't actually do anything (the onclick attributes code itself needs to be returning false. As a result the form is being submitted and the AJAX request is cancelled.
The simplest fix would be this:
<input type="submit" onclick="return updateStock('Penguincard', 'Penguin card');" value="Update">
However, it would probably be better to use jQuery to bind the event handler:
$(':submit').on('click', function(e) {
e.preventDefault();
updateStock('Penguincard', 'Penguin card');
});
This line is the issue:
onclick="updateStock("Penguincard", "Penguin card");"
The double quotes inside the attribute are the problem. Convert them to single quotes. This is one reason why people like to use the jQuery delegates to add click events.

There is no alert when submitting a form using ajaxForm plugin

How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){

Categories

Resources